c++ - std::minmax initializer_list<T> 参数

标签 c++ c++11 std c++-standard-library minmax

也许这个问题有点理论,但我想知道定义 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/

相关文章:

c++ - 为什么我的 QRadioButtons 没有出现在我的 QGroupBox 中?

c++ - 新手在这里 : Different results on PC and MAC. 为什么?

c++ - alignas 会影响 sizeof 的值吗?

c++ - 关于标准 :cout in C++

c++ - 自动文件重命名 - const 变量正在改变它的值?

c++ - C++中的哈希表?

c++ - 使用 gcc 进行静态和动态链接

c++ - std::future 的错误用法?

c++ - 为什么不能用兼容类型的 std::tuple 按元素构造 std::tuple?

c++ - 在不同 DLL 之间传递的标准对象