也许这个问题有点理论,但我想知道定义 std::minmax
背后的设计动机是什么?像这样
template <class T>
pair<T,T> minmax (initializer_list<T> il);
这意味着,IMO,传递的对象,li
将被复制并且它的每个成员也必须是可复制构造的。
同时,std::min_element
(或者就此而言 std::max_element
)在仅传递容器迭代器的意义上更“高效”(无需实际复制整个容器)
template <class ForwardIterator>
ForwardIterator min_element (ForwardIterator first, ForwardIterator last);
编辑 - 基于 Joachim Pileborg 的评论,initializer_list<T>
对象没有被复制,所以我要指出我的问题 - 为什么 std::minmax
受限于此类对象而不是任意容器(可以说具有“非常量”性质)
最佳答案
对于您更新的问题:minmax
也可以与迭代器对的一般情况一起使用,它称为 minmax_element
。所以 minmax
本身只是一个方便的速记,可以像这样写出紧凑的东西:
// define a, b, c here
int min, max;
std::tie(min, max) = std::minmax({a, b, c});
...而不是这样写:
// define a, b, c here
int min, max;
auto list = {a, b, c};
auto result = std::minmax_element(list.begin(), list.end());
min = *result.first;
max = *result.second;
关于c++ - std::minmax initializer_list<T> 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27504051/