Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::min_element — finding the smallest element

std::min_element from <algorithm> returns an iterator to the first smallest element in a range. It does not sort the data. For an empty range it returns last, so check the iterator before reading the result.

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

Syntax

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

std::min_element from <algorithm> searches a valid range [first, last): it includes first but excludes last. It returns an iterator, not a copy of the value. The calls described here, without an execution policy, require at least forward iterators; the algorithm does not sort or rearrange elements.

The call std::min_element(first, last) uses the default ascending order. The form std::min_element(first, last, comp) lets you specify an order: comp(a, b) must mean that a precedes b. The comparator must define a strict weak ordering; do not use <=. If several elements are equivalent to the minimum under that ordering, the result points to the first of those elements in the range.

For an empty range, the result is last. Before using *it, check it != last, because dereferencing an end iterator is invalid. The result remains tied to the source data: do not use it after the data is destroyed or an operation invalidates the iterator.

For N elements, the algorithm performs exactly max(N - 1, 0) comparisons, giving linear time complexity. The example selects the first 2, at zero-based index 1. Iterator subtraction works here because std::array provides random-access iterators; it is not generally available for forward iterators.

Examples

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

int main() {
    const std::array<int, 5> values{7, 2, 5, 2, 9};
    const auto it = std::min_element(values.begin(), values.end());
    if (it != values.end()) {
        std::cout << "minimum=" << *it
                  << ", index=" << (it - values.begin()) << '\n';
    }
}

Result

minimum=2, 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