C++ Standard Library C++ STL Library

C++ <algorithm> - max_element() Function



The C++ algorithm::max_element function returns an iterator pointing to the largest element in the range [first,last). The elements are compared using operator< (in first version) or comp (in second version).

Syntax

//default version
template <class ForwardIterator> 
  ForwardIterator max_element (ForwardIterator first, 
                               ForwardIterator last);

//custom version
template <class ForwardIterator, class Compare>
  ForwardIterator max_element (ForwardIterator first, 
                               ForwardIterator last,
                               Compare comp);

Parameters

first Specify initial position of the forward iterator of the sequence to compare. The range used is [first,last).
last Specify final position of the forward iterator of the sequence to compare. The range used is [first,last).
comp A binary predicate that takes two elements in the range as arguments and returns a value convertible to bool. The returned value indicates whether the first argument is considered less than the second.

Return Value

Returns an iterator pointing to largest element in the range, or last if the range is empty.

Time Complexity

Linear i.e, Θ(n).

Example:

In the example below, the algorithm::max_element function is used to find out the largest element in the given range.

#include <iostream>
#include <algorithm>
using namespace std;

int main (){
  int Arr[] = {10, 5, 15, 45, 20, 55};
  int *p_min, *p_max;

  //finding minimum element in the array
  p_min = min_element(Arr, Arr+6);
  cout<<"The minimum element in Arr: "<<*p_min;

  //finding maximum element in the array
  p_max = max_element(Arr, Arr+6);
  cout<<"\nThe maximum element in Arr: "<<*p_max;

  return 0;
}

The output of the above code will be:

The minimum element in Arr: 5
The maximum element in Arr: 55

Example:

The example below shows how to use comp with algorithm::max_element function.

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

bool less_than (int i, int j) {
  return (i<j);
}

int main (){
  vector<int> vec= {10, 5, 15, 45, 20, 55};
  vector<int>::iterator p_min, p_max;

  //finding minimum element in the vector
  p_min = min_element(vec.begin(), vec.end(), less_than);
  cout<<"The minimum element in vec: "<<*p_min;

  //finding maximum element in the vector
  p_max = max_element(vec.begin(), vec.end(), less_than);
  cout<<"\nThe maximum element in vec: "<<*p_max;

  return 0;
}

The output of the above code will be:

The minimum element in vec: 5
The maximum element in vec: 55

❮ C++ <algorithm> Library