I have forgotten
my Password

Or login with:

  • Facebookhttp://facebook.com/
  • Googlehttps://www.google.com/accounts/o8/id
  • Yahoohttps://me.yahoo.com
ComputingStlAlgorithmsMin Max

//

Returns the element with the largest value
+ View version details

Definition

The max_element() algorithm is defined in the standard header <algorithm> and in the nonstandard backward-compatibility header <algo.h>.

Interface

#include <algorithm>
template < class ForwardIterator >
   ForwardIterator max_element(
      ForwardIterator first, 
      ForwardIterator last
   );
template < class ForwardIterator, class BinaryPredicate >
   ForwardIterator max_element(
      ForwardIterator first, 
      ForwardIterator last, 
      BinaryPredicate comp
   );

Parameters:
Parameter Description
first A forward iterator addressing the position of the first element in the range to be searched for the largest element
last A forward iterator addressing the position one past the final element in the range to be searched for the largest element
comp User-defined predicate function object that defines the sense in which one element is greater than another. The binary predicate takes two arguments and should return true when the first element is less than the second element and false otherwise

Description

Max_element finds the smallest element in the range [first, last).

The first version compares objects using operator< and the second compares objects using a function object comp.

Return Value

Returns the greater element in the range [first, last).

Complexity

The complexity is linear; performs exactly (last - first) - 1 comparisons.
Example:

Example - max_element algorithm
Problem
This program illustrates the use of the STL max_element() algorithm (default version) to find the maximum value in a vector of integers.
Workings
#include <iostream>
#include <vector>
#include <algorithm>
 
using namespace std;
 
int main()
{
  int a[] = {2, 6, 10, 8, 4};
  vector<int> v(a, a+5);
 
  cout <<"\nHere are the integer values in the vector:\n";
  for (vector<int>::size_type i=0; i<v.size(); i++)
    cout <<v.at(i)<<" ";
 
  cout <<"\nThe maximum value in the vector is "<<*max_element(v.begin(), v.end())<<".";
 
  return 0;
}
Solution
Output:

Here are the integer values in the vector:
2 6 10 8 4

The maximum value in the vector is 10.
References