How to use the max_element() function in C++

The max_element() function accepts a list of values and returns the iterator that points to the largest value among all the elements in the list. This function is available in <algorithm.h>. The max_element() function helps to write code faster, as we do not waste time writing this simple logic.

Parameters

The max_element() function accepts the following parameters.

  • first: This is the iterator that points to the start of the array or vector where we want to find the maximum.

  • second_value: This is the iterator that points to the last position of the array or vector where we want to find the maximum.

  • comparator: This is an optional parameter that specifies the condition to pick the element from the array. In other words, you can pass a function that accepts two values and returns a Boolean value denoting which value to pick out of the two given values.

Return

The max_element() returns an iterator that points to the largest element in the array.

Let’s look at the code now.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> vec = {3,7,2,5,6,4,9};
auto it = max_element(vec.begin(), vec.end());
cout << "The largest element is " << *it;
return 0;
}

Explanation:

  • From lines 1 to 3, we import the required header files.
  • In line 7, we create a vector of integers.
  • In line 9, we call the max_element() function and pass the required parameters.
  • Finally, in line 10, we print the largest element in the vector.

We used *it to print the element, as the function returns a pointer to the largest element.

Free Resources