Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::max_element — iterator to the largest element

std::max_element searches a range and returns an iterator to its first largest element. An empty range yields last; an optional comparator determines the ordering.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <algorithm>
std::max_element(first, last)
std::max_element(first, last, comp)

std::max_element, declared in <algorithm>, searches a valid range [first, last). It returns an iterator, not a value copy; equivalent maxima select the first occurrence. It does not sort the range.

For an empty range, the result is last. Check it != last before using *it: dereferencing the end iterator is invalid. Iterators must meet forward iterator requirements; an input-only iterator is insufficient.

In C++23, the classic overload without an explicit comparator uses std::less{} rather than applying operator< directly. This matters for pointers: std::less{} provides a strict total order for pointers, whereas built-in < need not. A custom comp(a, b) must mean that a precedes b and define a strict weak ordering. Do not use <=: an element must not precede itself. “Largest” means last under that ordering, not necessarily numerically largest.

For N elements, the algorithm performs exactly max(N - 1, 0) comparisons, giving linear complexity. The example selects the first of two maxima. Iterator subtraction works here because std::array provides random-access iterators; it is not a general requirement of this algorithm.

Examples

#include <algorithm>
#include <array>
#include <iostream>

int main() {
    const std::array<int, 5> values{3, 9, 4, 9, 2};
    const auto it = std::max_element(values.begin(), values.end());

    if (it != values.end()) {
        std::cout << "max=" << *it << ", index="
                  << (it - values.begin()) << '\n';
    }
}

Result

max=9, index=1

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources