为什么std :: min仅支持initializer_list? [英] Why does std::min only support initializer_list?
问题描述
我们可以通过以下方式使用 std :: min
:
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});
但是为什么不能使用 std :: vector
或 std :: list
,因为模板中的参数是 initializer_list
.
But why can't use a std::vector
or std::list
, Because the param in the template is initializer_list
.
template <class T, class Compare>
pair<T,T> minmax (initializer_list<T> il, Compare comp);
这种设计的原因是什么?
What is the reason for this design?
推荐答案
要解释为什么它不接受容器",请考虑以下语义:
To explain "why it doesn't accept a container", take the semantic into consideration:
std :: min({"foo","bar","hello"})
std :: min()
的语义表示在输入参数中找到最小值".因此, std :: min()
/ std :: max()
接受两个参数,或者将initializer_list用作更多参数".
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()
无法提供通过容器迭代"的功能,因为容器被视为参数".
std::min()
doesn't provide the ability to "iterate through a container", because a container is considered as "a parameter".
要查找容器中的最小值,请在C +中找到 std :: min_element()
和eerorika的建议 std :: ranges :: min()
+20应该更好.
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.
对于 std :: min_element()
的用法,您可以参考如何获取最大值(或min)值中的值?.
For std::min_element()
usage, you may refer to How can I get the max (or min) value in a vector?.
这篇关于为什么std :: min仅支持initializer_list?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!