Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::minmax — minimum and maximum

std::minmax from <algorithm> finds the minimum and maximum together. The two-argument overload returns a pair of references, whereas the initializer-list overload returns a pair of copied values.

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

Syntax

#include <algorithm>

template<class T>
constexpr std::pair<const T&, const T&> minmax(const T& a, const T& b);
template<class T, class Compare>
constexpr std::pair<const T&, const T&> minmax(const T& a, const T& b, Compare comp);
template<class T>
constexpr std::pair<T, T> minmax(std::initializer_list<T> t);
template<class T, class Compare>
constexpr std::pair<T, T> minmax(std::initializer_list<T> t, Compare comp);

std::minmax from <algorithm> returns the minimum in .first and the maximum in .second. It compares using < by default; an optional comp must define a strict weak ordering. Arguments must allow deduction of a common template type T.

std::minmax(a, b) performs exactly one comparison and returns std::pair<const T&, const T&>. For equivalent arguments, .first refers to a and .second to b. The objects must remain alive while you use those references. auto p = std::minmax(8, 3); leaves dangling references after the semicolon: copying the pair does not copy the values.

std::minmax({8, 3, 5}) returns std::pair<T, T> containing copies; T must be copy-constructible and the list must not be empty. Ties select the first minimum and last maximum. For N elements, the comparison count is at most 3N/2.

The example demonstrates both forms without dangling references. Both print 3 8. These are std::minmax overloads, not the separate std::ranges::minmax API.

Examples

#include <algorithm>
#include <iostream>

int main() {
    int a = 8;
    int b = 3;
    const auto refs = std::minmax(a, b);
    const auto values = std::minmax({8, 3, 5, 8});

    std::cout << refs.first << ' ' << refs.second << '\n';
    std::cout << values.first << ' ' << values.second << '\n';
}

Result

3 8
3 8

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