Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::min — selecting the smallest value

std::min from <algorithm> selects the smaller of two arguments or the minimum of a nonempty list. The two-argument overload returns a reference, while the list overload returns a copy; an optional comparator defines the ordering.

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

Syntax

#include <algorithm>

std::min(a, b)
std::min(a, b, comp)
std::min({a, b, c})
std::min({a, b, c}, comp)

std::min requires <algorithm>. In C++23, the overloads without an explicit comparator use operator<, not std::less{}. They therefore do not provide the strict total order for pointers guaranteed by std::less. An optional comp must define a strict weak ordering. Equivalence means neither argument precedes the other under that ordering.

std::min(a, b) returns const T& referring to the smaller argument, or the first when equivalent. It performs exactly one comparison. Deduction requires a common T: std::min(1, 2.0) does not compile; use matching types or explicit std::min<double>(1, 2.0).

std::min({a, b, c}) returns a copy of the first minimum by value. The list must be nonempty, and T must be copy-constructible. For N elements it performs exactly N - 1 comparisons.

Watch lifetimes: const int& r = std::min(1, 2); leaves a dangling reference after the statement. Storing the result as int or auto makes a safe copy. In the example, comp uses >, so the minimum under the reversed ordering is the larger number.

Examples

#include <algorithm>
#include <iostream>

int main() {
    int a = 7;
    int b = 3;
    int pair_min = std::min(a, b);
    int list_min = std::min({7, 3, 5});
    int reverse_min = std::min(a, b, [](int x, int y) {
        return x > y;
    });
    std::cout << pair_min << ' ' << list_min << ' ' << reverse_min << '\n';
}

Result

3 3 7

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