以下代码在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;
});
最佳答案
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/