max_element和min_element
max_element和min_element:
函数作用:返回最大值和最小值,max_element(first,end,cmp);其中cmp为可选择参数!
first, last:
Input iterators to the initial and final positions of the sequence to use. The range used is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
comp:
Comparison function object that, taking two values of the same type than those contained in the range, returns true if the first argument is to be considered less than the second argument, and false otherwise.
示例程序:
[cpp]
//结构体,普通元素
#include <iostream>
#include <algorithm>
using namespace std;
bool myfn(int i, int j) { return i<j; }
struct myclass {
bool operator() (int i,int j) { return i<j; }
} myobj;
int main () {
int myints[] = {3,7,2,5,6,4,9};
cout << “最小的元素是 :” << *min_element(myints,myints+7) << endl;
cout << “最大的元素是 :” << *max_element(myints,myints+7) << endl;
cout << “最小的元素是 :” << *min_element(myints,myints+7,myfn) << endl;
cout << “最大的元素是 :” << *max_element(myints,myints+7,myfn) << endl;
cout << “最小的元素是: ” << *min_element(myints,myints+7,myobj) << endl;
cout << “最大的元素是”: << *max_element(myints,myints+7,myobj) << endl;
return 0;
}
[/cpp]
输出结果:
[cpp]
最小元素是 2
最大元素是 9
最小元素是 2
最大元素是 9
最小元素是 2
最大元素是 9
[/cpp]