min_element是求容器中的最小值,有两种函数重载:
第一种,单纯的比较大小:
template<class _FwdIt> inline _FwdIt min_element(_FwdIt _First, _FwdIt _Last)第二种,按照函数要求比较大小,可以是普通的比较函数,也可以是仿函数:
template<class _FwdIt, class _Pr> inline _FwdIt min_element(_FwdIt _First, _FwdIt _Last, _Pr _Pred)max_element是求容器中的最大值,同样有两种函数重载:
第一种,单纯的比较大小:
template<class _FwdIt> inline _FwdIt max_element(_FwdIt _First, _FwdIt _Last)第二种,按照函数要求比较大小,可以时普通函数也可以是仿函数:
template<class _FwdIt, class _Pr> inline _FwdIt max_element(_FwdIt _First, _FwdIt _Last, _Pr _Pred)程序案例:
#include<iostream> #include<vector> #include<algorithm> using namespace std; template<typename T> int PushNum(T &vec, int first, int last) { int ret = 0; if (first > last) { ret = -1; cout << "function PushNum first > last error : " << ret << endl; } while (first <= last) { vec.insert(vec.end(), first); first++; } return ret; } void print(int ele) { cout << ele << " "; } bool absCmp(int ele1, int ele2) { return (abs(ele1) < abs(ele2)); } template<typename T> class CmpClass{ public: CmpClass() {} bool operator()(T t1, T t2) { return ((1 / pow(2.17,t1)) < (1 / pow(2.17, t2))); } }; int main(){ vector<int> vec; PushNum(vec, -5, 13); for_each(vec.begin(), vec.end(), print); cout << endl; int min_ele = *min_element(vec.begin(), vec.end()); int max_ele = *max_element(vec.begin(), vec.end()); cout << min_ele << " " << max_ele << endl; int min_func = *min_element(vec.begin(), vec.end(), absCmp); int max_func = *max_element(vec.begin(), vec.end(), absCmp); cout << min_func << " " << max_func << endl; int min_class = *min_element(vec.begin(), vec.end(), CmpClass<int>()); int max_class = *max_element(vec.begin(), vec.end(), CmpClass<int>()); cout << min_class << " " << max_class << endl; system("pause"); return 0; }输出结果:
第一次单纯按照数值的大小进行比较,找到最大最小值,第二次按照绝对值大小比较,找出最大最小值,第三个的仿函数用了一个稍微复杂点的函数,同样是找到最大最小值。
注意:
如果有多个最大或者最小值,求得的是第一个最大或者最小值还是最后一个最大值或者最小值,关键还是看自定义的比较函数有没有等于号,这个看下min_element或者max_element源码就知道啦。