C++中的max_element与min_element

scorlw 发布于

C++中的max_element()与min_element()

c++

max_element()与min_element()都定义于头文件 ,分别实现了返回区间 [first,last)中第一个最大值和第一个最小值对应的迭代器

实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// min_element/max_element example
#include <iostream> // std::cout
#include <algorithm> // std::min_element, std::max_element

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};

// using default comparison:
std::cout << "The smallest element is " << *std::min_element(myints,myints+7) << '\n';
std::cout << "The largest element is " << *std::max_element(myints,myints+7) << '\n';

// using function myfn as comp:
std::cout << "The smallest element is " << *std::min_element(myints,myints+7,myfn) << '\n';
std::cout << "The largest element is " << *std::max_element(myints,myints+7,myfn) << '\n';

// using object myobj as comp:
std::cout << "The smallest element is " << *std::min_element(myints,myints+7,myobj) << '\n';
std::cout << "The largest element is " << *std::max_element(myints,myints+7,myobj) << '\n';

return 0;
}

IO:

1
2
3
4
5
6
7
输出:
The smallest element is 2
The largest element is 9
The smallest element is 2
The largest element is 9
The smallest element is 2
The largest element is 9

原文地址:https://blog.csdn.net/u010510020/article/details/73351262