c++ - std::partial_sum 和 std::inclusive_scan 有什么区别?

标签 c++ numeric stl-algorithm c++17

在阅读 std::inclusive_scan 时,似乎没有任何例子。
我觉得它与 std::partial_sum 非常相似.

partial_sum:

template< class InputIt, class OutputIt >
OutputIt partial_sum( InputIt first,
                      InputIt last, OutputIt d_first );

inclusive_scan:

template< class InputIt, class OutputIt >
OutputIt inclusive_scan( InputIt first,
                         InputIt last, OutputIt d_first );

有人可以详细说明他们的区别吗?我什么时候会选择其中之一?

最佳答案

std::inclusive_scan 的文档说明:

In other words, the summation operations may be performed in arbitrary order. The behavior is nondeterministic if binary_op is not associative.

std::partial_sum 的文档毫无保留地声明:

*(d_first+k) = *first + *(first+1) + ... + *(first+k);

因此,std::inclusive_scan 等价于 std::partial_sum 只有当 binary_op 是关联的,即当 (a opb)opc = aop (bopc).

在非关联 binary_op 的情况下,std::partial_sum 将产生确定性结果,而您不知道 std 会发生什么: :inclusive_scan.

关于c++ - std::partial_sum 和 std::inclusive_scan 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38006107/

相关文章:

c++ - 在2D vector 中使用第三个[]有什么目的?

c++ - 虚拟模板设计

r - R 中 log2 的矩阵 as.numeric 的子集

r - 字符到数字摘要失败

r - 制作矩阵数字和名称顺序

c++ - 避免原始循环并改用 std::algorithm

c++ - 以模板化函数作为参数的 STL 算法

c++ - C++ iomanip 库的有效使用

nvcc 不支持 C++11 函数 iota()?