简单记录下我的学习过程 (代码为主)
min_element、max_element 找最小、最大值。 非常easy没什么大作用
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; /******************************************************************************************* template <class ForwardIterator> ForwardIterator min_element ( ForwardIterator first, ForwardIterator last ); template <class ForwardIterator, class Compare> ForwardIterator min_element ( ForwardIterator first, ForwardIterator last, Compare comp ); eg: template <class ForwardIterator> ForwardIterator min_element ( ForwardIterator first, ForwardIterator last ) { ForwardIterator lowest = first; if (first==last) return last; while (++first!=last) if (*first<*lowest) // or: if (comp(*first,*lowest)) for the comp version lowest=first; return lowest; } ********************************************************************************************/ /******************************************************************************************** template <class ForwardIterator> ForwardIterator max_element ( ForwardIterator first, ForwardIterator last ); template <class ForwardIterator, class Compare> ForwardIterator max_element ( ForwardIterator first, ForwardIterator last, Compare comp ); eg: template <class ForwardIterator> ForwardIterator max_element ( ForwardIterator first, ForwardIterator last ) { ForwardIterator largest = first; if (first==last) return last; while (++first!=last) if (*largest<*first) // or: if (comp(*largest,*first)) for the comp version largest=first; return largest; } ********************************************************************************************/ 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: cout << "The smallest element is " << *min_element(myints,myints+7) << endl; cout << "The largest element is " << *max_element(myints,myints+7) << endl; // using function myfn as comp: 函数 cout << "The smallest element is " << *min_element(myints,myints+7,myfn) << endl; cout << "The largest element is " << *max_element(myints,myints+7,myfn) << endl; // using object myobj as comp: 函数对象 cout << "The smallest element is " << *min_element(myints,myints+7,myobj) << endl; cout << "The largest element is " << *max_element(myints,myints+7,myobj) << endl; return 0; } /********* Output: 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 *********/