取容器中的最大或最小值:max_element, min_element。
代码
//see: http://www.cplusplus.com/reference/algorithm/max_element/
#include <iostream>
#include <list>
#include <algorithm>
bool my_compare(int x, int y)
{
return abs(x) < abs(y);
}
class MyCompare {
public:
bool operator()(int x, int y)
{
return abs(x) < abs(y);
}
};
int main()
{
std::list<int> values;
values.push_back(1);
values.push_back(3);
values.push_back(-3);
values.push_back(-1);
int the_max = *std::max_element(values.begin(), values.end());
int the_min = *std::min_element(values.begin(), values.end());
std::cout<<"max: "<<the_max<<std::endl;
std::cout<<"min: "<<the_min<<std::endl;
the_max = *std::max_element(values.begin(), values.end(), my_compare);
the_min = *std::min_element(values.begin(), values.end(), my_compare);
std::cout<<"max: "<<the_max<<std::endl;
std::cout<<"min: "<<the_min<<std::endl;
MyCompare myCompare;
the_max = *std::max_element(values.begin(), values.end(), myCompare);
the_min = *std::min_element(values.begin(), values.end(), myCompare);
std::cout<<"max: "<<the_max<<std::endl;
std::cout<<"min: "<<the_min<<std::endl;
return 0;
}
运行结果
max: 3
min: -3
max: 3
min: 1
max: 3
min: 1