CKTIS / C++
std::max — selecting the largest value
std::max from <algorithm> selects the larger of two arguments or the largest element of a nonempty initializer list. It supports custom comparison; the two-value overload returns a reference, whereas the list overload returns a copy.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <algorithm>
template<class T>
constexpr const T& max(const T& a, const T& b);
template<class T, class Compare>
constexpr const T& max(const T& a, const T& b, Compare comp);
template<class T>
constexpr T max(std::initializer_list<T> values);
template<class T, class Compare>
constexpr T max(std::initializer_list<T> values, Compare comp);std::max is available in <algorithm>. It compares using < by default; optional comp(x, y) means that x precedes y and must define a strict weak ordering. Equivalent values select the first argument or the first maximal list element.
The two-value overload returns const T& and performs exactly one comparison. Both arguments must deduce the same T: std::max(2, 3.5) does not compile; std::max<double>(2, 3.5) explicitly chooses the type.
The std::initializer_list<T> overload returns a copy and requires copy-constructible T and a nonempty list. For N elements, it performs exactly N - 1 comparisons. An empty list violates its precondition.
Watch lifetimes: const auto& r = std::max(1, 2); leaves a dangling reference after the semicolon. Use auto r = std::max(1, 2); to retain the value. In the example, custom comparison selects the number with the larger last digit. The cited sources are a maintained working draft, not a frozen C++23 publication.
Examples
#include <algorithm>
#include <iostream>
int main() {
int a = 4;
int b = 9;
auto by_last_digit = [](int x, int y) {
return x % 10 < y % 10;
};
std::cout << std::max(a, b) << '\n';
std::cout << std::max({4, 9, 7}) << '\n';
std::cout << std::max(24, 19, by_last_digit) << '\n';
}
Result
9 9 19
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.