max_element() in C++ STL

The C++ Standard Library consists of the header, <algorithm> which defines a collection of functions (principally designed to deal with a range of elements). max_element() is a method in the STL that returns an iterator pointing to the largest value in a given container (arrays, vectors, lists) in the specified range.


max_element(iterator_begin, iterator_end); //find largest element from [begin,end)
max_element(iterator_begin, iterator_end, comparator); //for comparison based on a pre defined function

Parameters: The max_element() method accepts 3 parameters

  • iterator_begin: Random access iterator to the initial position
  • iterator_end: Random access iterator to the final position ( Note: the range is [iterator_begin,iterator_end) )
  • comparator: Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool.

Return value: An iterator to largest value in the range, or iterator_end if the range is empty.

Example of max_element() method

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

bool absolute(int a, int b)
    return (abs(a) < abs(b));

int main()
    vector<int> v;

    vector<int>::iterator it = max_element(v.begin(),v.end()); 
    cout<<"Max element: "<< *it << endl;

    vector<int>::iterator it2 = max_element(v.begin(), v.end(), absolute); //using a defined comparator
    cout<<"Max element (absolute): "<< *it2 << endl;


Max element: 8
Max element (absolute): -10

This article is written by

Please comment below, if you have any doubts or find any error in the above article.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top
[gravityforms id="5" description="false" titla="false" ajax="true"]