c++ max_elment和min_element
2012-06-28 00:48 youxin 阅读(726) 评论(0) 编辑 收藏 举报max_element和min_element用来求一个范围内的最大值和最小值
template <class ForwardIterator> ForwardIterator max_element ( ForwardIterator first, ForwardIterator last ); template <class ForwardIterator, class Compare> ForwardIterator max_element ( ForwardIterator first, ForwardIterator last, Compare comp );
int max= *max_element(v.begin(),v.end()); //注意返回的是一个迭代器,*取值
int max= *min_element(energy.begin(),energy.end()); //求最小值
// min_element/max_element #include <iostream> #include <algorithm> using namespace std; 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; }
The example illustrates how the comparison object can be either a function or an object whose class defines theoperator() member. In this case both have been defined to perform a standard less-than comparison.
Output:
The smallest element is 2 The largest element is 9