STL max_element

来源:互联网 发布:单片机实验教程 编辑:程序博客网 时间:2024/06/05 20:29

取容器中的最大或最小值: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: 3min: -3max: 3min: 1max: 3min: 1
0 0
原创粉丝点击