min_element | function template |
template <class ForwardIterator> ForwardIterator min_element ( ForwardIterator first, ForwardIterator last ); template <class ForwardIterator, class Compare> ForwardIterator min_element ( ForwardIterator first, ForwardIterator last, Compare comp ); | <algorithm> |
Return smallest element in range
Returns an iterator pointing to the element with the smallest value in the range [first,last). The comparisons are performed using either operator< for the first version, orcomp for the second; An element is the smallest if no other element compares less than it (it may compare equal, though).
The behavior of this function template is equivalent to:
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; } |
Parameters
-
first, last
- Input iterators to the initial and final positions of the sequence to use. The range used is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last. comp
- Comparison function object that, taking two values of the same type than those contained in the range, returns true if the first argument is to be considered less than the second argument, and false otherwise.
Return value
Iterator to smallest value in the range.#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
class student{
public:
int key;
int value;
bool operator<(student s){
return key<s.key;
}
};
bool cmp(student a,student b){
return a.key<b.key;
}
int main(){
vector<student> vec(6);
int i;
vector<student>::iterator it;
vec[0].key=15;
vec[0].value=1;
vec[1].key=2;
vec[1].value=2;
vec[2].key=2;
vec[2].value=2;;
vec[3].key=3;
vec[3].value=3;
vec[4].key=3;
vec[4].value=4;
vec[5].key=7;
vec[5].value=5;
// sort(vec.begin(),vec.end(),cmp);
for(i=0;i<6;i++)
cout<<vec[i].key<<endl;
it=max_element(vec.begin(),vec.end());
cout<<(*it).key<<endl;
}