![]() |
VOOZH | about |
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:
17 87
std::max_element(first, last, comp);
Example 1: Find Maximum Element in Array
87
Example 2: Finding Element Having Maximum Remainder After Division with 5
For this purpose, we have to use the custom comparator function.
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.
Anmol 23
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:
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.