c++ - “std::reduce”的正确用法是什么

标签 c++

以下代码在MSVC上编译,但在GCC上失败。似乎GCC要求解引用的迭代器和init的类型相同,即使根据this reference并没有这样的要求。请注意,如果我将std::reduce()替换为std::accumulate(),则可以使用。

std::random_device e;
std::uniform_int_distribution<> dist(1, 10);
const int n = 10;
std::vector<int> v(n);
std::generate(v.begin(), v.end(), [&]() {return dist(e); });
const auto result = std::reduce(v.begin(), v.end(), std::make_pair(0, 0),
    [](std::pair<int,int> sum,int n) {
        if (n % 2 == 1) sum.first += n;
        else sum.second += n;
        return sum;
    });

最佳答案

[reduce]/5

Mandates: All of

  • binary_­op(init, *first),
  • binary_­op(*first, init),
  • binary_­op(init, init), and
  • binary_­op(*first, *first)

are convertible to T.



您的lambda无法用于binary_­op(*first, *first),因此gcc拒绝它是正确的。

关于c++ - “std::reduce”的正确用法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62313504/

相关文章:

c++ - 将一对 move 到 vector 中

c++ - 如何获取GLSL编译错误的行号

c++ - 使用 cygwin 在 Windows 上安装 GMP

c++ - 从转换运算符提取返回和参数类型到函数指针

c++ - 彩票模拟器返回垃圾值而不是用户乐透号码和中奖号码

c++ - For 循环性能差异,以及编译器优化

c++ - 构造函数不设置成员变量

c++ - move 构造函数相对于采用 bool 表示是复制还是 move 的复制构造函数有什么优势?

c++ - 模板化类如何解析在其类型之一上调用的重载非成员函数?

c++ - 什么结果没有意义?