VOOZH about

URL: https://www.geeksforgeeks.org/cpp/max_element-in-cpp/

⇱ max_element in C++ STL - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

max_element in C++ STL

Last Updated : 19 Jan, 2026

The std::max_element() function in C++ is an STL algorithm used to find the maximum element within a given range. It is defined inside the <algorithm> header file. In this article, we will learn how to find the maximum element in the range using std::max_element() in C++.

Example:


Output
17
87

Syntax

std::max_element(first, last, comp);

Parameters

  • first: Iterator to the first element of the range.
  • last: Iterator to the element just after the last element of the range.
  • comp: Binary comparator function, functor or lambda expression that compares two elements in the range. By default, it is set as < operator.

Return Value

  • Returns an iterator to the largest element in the range.
  • When the range is empty, it returns iterator to the last.

Example 1: Find Maximum Element in Array


Output
87

Example 2: Finding Element Having Maximum Remainder After Division with 5

For this purpose, we have to use the custom comparator function.


Output
33

Example 3: Find Maximum Element in Vector of User Defined Data Type

We have to use custom comparator again to determine how to compare user defined data type on any of its property.


Output
Anmol 23

How std::max_element() Works Internally

1. It starts by assuming the first element is the maximum.

2. It then iterates sequentially from first to last.

3. For each element, it compares it with the current maximum using:

  • operator< (default), or
  • the user-defined comparator.

4. If a larger element is found, the iterator to that element becomes the new maximum.

5. After reaching the end, it returns an iterator pointing to the largest element.

Comment
Article Tags: