Translations of this page?:

max_element

#include <algorithm>
 
template< class ForwardIterator >
ForwardIterator max_element( ForwardIterator first, ForwardIterator last );
 
template< class ForwardIterator, class Compare >
ForwardIterator max_element( ForwardIterator first, ForwardIterator last, Compare p );

Finds the greatest element in the range [first, last). One version of the function uses operator< to compare the elements, another uses the compare function p.

Parameters

first, last - the range of elements to be examined

comp - comparison function which returns true if the first parameter is less than the second

Return value

iterator pointing to the largest element

Equivalent function

First version:

template<class ForwardIterator>
ForwardIterator max_element(ForwardIterator first, ForwardIterator last)
{
    if (first == last) {
        return last;
        }
    ForwardIterator largest = first;
    ++first;
    for (; first != last; ++first) {
        if (*largest < *first) {
            largest = first;
        }
    }
    return largest;
}

Second version:

template<class ForwardIterator, class Compare>
ForwardIterator max_element(ForwardIterator first, ForwardIterator last, Compare comp)
{
    if (first == last) {
        return last;
        }
    ForwardIterator largest = first;
    ++first;
    for (; first != last; ++first) {
        if (comp(*largest, *first)) {
            largest = first;
        }
    }
    return largest;
}

Example

#include <algorithm>
#include <iostream>
#include <vector>
 
int main()
{
    int data[] = { 3, 1, 4, 1, 5, 9 };
    std::vector<int> v(data, data+6);
 
    std::vector<int>::iterator result = std::max_element(v.begin(), v.end());
    std::cout << "max element at: " << std::distance(v.begin(), result);
 
    return 0;
}

Output:

max element at: 5

Complexity

linear in the distance between first and last

See also

 
• • • SitemapRecent changesRSScc