max_element和min_element

来源:互联网 发布:js判断按钮是否被点击 编辑:程序博客网 时间:2024/05/21 12:20

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.

示例程序:

01//结构体,普通元素
02#include <iostream>
03#include <algorithm>
04using namespace std;
05 
06bool myfn(inti,int j) { returni<j; }
07 
08struct myclass {
09bool operator() (inti,intj) { return i<j; }
10} myobj;
11 
12int main () {
13int myints[] = {3,7,2,5,6,4,9};
14 
15cout << "最小的元素是 :"<< *min_element(myints,myints+7) << endl;
16cout << "最大的元素是 :"<< *max_element(myints,myints+7) << endl;
17 
18cout << "最小的元素是 :"<< *min_element(myints,myints+7,myfn) << endl;
19cout << "最大的元素是 :"<< *max_element(myints,myints+7,myfn) << endl;
20 
21cout << "最小的元素是: "<< *min_element(myints,myints+7,myobj) << endl;
22cout << "最大的元素是": << *max_element(myints,myints+7,myobj) << endl;
23 
24return 0;
25}

输出结果:

1最小元素是 2
2最大元素是 9
3最小元素是 2
4最大元素是 9
5最小元素是 2
6最大元素是 9
0 0