Open In App

max_element in C++ STL

Last Updated : 18 Oct, 2024
Comments
Improve
Suggest changes
49 Likes
Like
Report

The std::max_element() in C++ is an STL algorithm that is used to find the maximum element in the 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

std::max_element() 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.

More Examples of std::max_element()

We can find the maximum element of the given range using std::max_element(). This range can be std::vector, array, list or any other container.

Example 1: Find Maximum Element in Array


Output
87

Time Complexity: O(n), where n is the number of elements in array.
Auxiliary Space: O(1)

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

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


Output
33

Time Complexity: O(n), where n is the number of elements in vector.
Auxiliary Space: O(1)

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

Time Complexity: O(n), where n is the number of elements in the vector.
Auxiliary Space: O(1)

Working of std::max_element()

std::max_element() implements linear search algorithm to find the largest element in the range. It compares each element of the range one by one using the iterator/pointer provided to it as arguments. This is the reason why it gives O(n) linear time complexity.

std::max_element() not specialized for sorted containers such as std::set, std::map, etc. and still will compare all the elements of these containers to find the maximum element.


max_element() and min_element() in C++ STL
Visit Course explore course icon
Practice Tags :

Similar Reads