1. 程式人生 > >C++中min_element()與max_element()(取容器中的最大最小值)

C++中min_element()與max_element()(取容器中的最大最小值)

min_element 和 max_element

標頭檔案:#include<algorithm>

作用:返回容器中最小值和最大值的指標。max_element(first,end,cmp);其中cmp為可選擇引數!

例1

#include<iostream>
#include<algorithm>
using namespace std;

bool cmp(int a,int b)
{
	return a<b;
}
int main()
{
	int num[]={2,3,1,6,4,5};
	cout<<"最小值是 "<<*min_element(num,num+6)<<endl;
	cout<<"最大值是 "<<*max_element(num,num+6)<<endl;
	cout<<"最小值是 "<<*min_element(num,num+6,cmp)<<endl;
	cout<<"最大值是 "<<*max_element(num,num+6,cmp)<<endl;
	return 0; 
}

例2 

vector<cv::DMatch> matches;
cv::BFMatcher matcher ( cv::NORM_HAMMING );
matcher.match ( descriptors_ref_, descriptors_curr_, matches );
// select the best matches
float min_dis = std::min_element (
                        matches.begin(), matches.end(),
                       [] ( const cv::DMatch& m1, const cv::DMatch& m2 )
{
        return m1.distance < m2.distance;
} )->distance;