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.
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.
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;}
max_element()
function and pass the required parameters.We used
*it
to print the element, as the function returns a pointer to the largest element.