We can use std::min
in below way:
// 1.
int a = 1, b = 2;
std::min(a, b);
// 2.
std::min({1,2,3,4});
But why can\'t use a std
To explain "why it doesn't accept a container", take the semantic into consideration:
std::min({ "foo", "bar", "hello" })
The semantic of std::min()
means "find the minimum value in the input parameters". Thus std::min()
/std::max()
takes two arguments, or an initializer_list as "more arguments".
std::min()
doesn't provide the ability to "iterate through a container", because a container is considered as "a parameter".
To find the min value in a container, there is std::min_element()
, and eerorika's suggestion std::ranges::min()
in C++20 should be better.
For std::min_element()
usage, you may refer to How can I get the max (or min) value in a vector?.