#include <algorithm>
forward_iterator min_element( forward_iterator start, forward_iterator end );
forward_iterator min_element( forward_iterator start, forward_iterator end, BinPred p );
The min_element() function returns an iterator to the smallest element in the range [start,end).
If the binary predicate p is given, then it will be used instead of the < operator to determine the smallest element.
Example
// 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 the operator() member. In this case both have been defined to perform a standard less-than comparison.
Output:
The smallest element is 2The largest element is 9The smallest element is 2The largest element is 9The smallest element is 2The largest element is 9