Why does std::min only support initializer_list?

后端 未结 3 1255
遇见更好的自我
遇见更好的自我 2021-01-24 00:41

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

3条回答
  •  囚心锁ツ
    2021-01-24 01:12

    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?.

提交回复
热议问题