The braces create an initializer list of four values.
The list form checks all of them.
It returns 2 as a copy.
Example 3 — Custom rule
Choose the number with the smaller absolute value.
C++
#include <algorithm>
#include <cstdlib>
#include <iostream>
int main() {
int m = std::min({-5, 3, -1, 4}, [](int a, int b) {
return std::abs(a) < std::abs(b);
});
std::cout << "Closest to zero: " << m << '\n';
return 0;
}
Output
Closest to zero: -1
How It Works
The lambda compares the size of each number, ignoring the sign.
The absolute values are 5, 3, 1 and 4, and 1 is the smallest.
That belongs to -1, so -1 is returned.
Frequently Asked Questions
In C++, std::min() returns the smaller of two values, or the smallest in a list. Include <algorithm> to use it.
Include <algorithm>. It has been part of C++ since C++98, so every modern compiler supports it.
It returns the smaller of the two values (a reference), or the smallest value of an initializer list. If values are equal, the first one is returned.
It returns the first argument.
std::min() compares values you pass in. std::min_element() searches a range and returns an iterator.