max_element

Syntax:

  #include <algorithm>
  forward_iterator max_element( forward_iterator start, forward_iterator end );
  forward_iterator max_element( forward_iterator start, forward_iterator end, BinPred p );

The max_element() function returns an iterator to the largest 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 largest element.

For example, the following code uses the max_element() function to determine the largest integer in an array and the largest character in a vector of characters:

  int array[] = { 3, 1, 4, 1, 5, 9 };
  unsigned int array_size = sizeof(array) / sizeof(array[0]);
  cout << "Max element in array is " << *max_element(array, array+array_size) << endl;
 
  vector<char> v;
  v.push_back('a'); v.push_back('b'); v.push_back('c'); v.push_back('d');
  cout << "Max element in the vector v is " << *max_element(v.begin(), v.end()) << endl;

When run, the above code displays this output:

   Max element in array is 9
   Max element in the vector v is d

Related Topics: max, min, min_element