std::partial_sum
来自cppreference.com
                    
                                        
                    
                    
                                                            
                    |  | 该页由英文版wiki使用Google Translate机器翻译而来。 
 该翻译可能存在错误或用词不当。鼠标停留在文本上可以看到原版本。你可以帮助我们修正错误或改进翻译。参见说明请点击这里. | 
| 在头文件 <numeric> 中定义
  | ||
| template< class InputIt, class OutputIt > OutputIt partial_sum( InputIt first, InputIt last, OutputIt d_first ); | (1) | |
| template< class InputIt, class OutputIt, class BinaryOperation > OutputIt partial_sum( InputIt first, InputIt last, OutputIt d_first, | (2) | |
计算的部分和的范围
[first, last)子范围中的元素,并且将它们写入到的范围内开始,d_first。使用operator+总结的第一个版本,第二个版本使用给定的二进制功能的op.原文:
Computes the partial sums of the elements in the subranges of the range 
[first, last) and writes them to the range beginning at d_first. The first version uses operator+ to sum up the elements, the second version uses the given binary function op.相同的操作
*(d_first) = *first; *(d_first+1) = *first + *(first+1); *(d_first+2) = *first + *(first+1) + *(first+2); *(d_first+3) = *first + *(first+1) + *(first+2) + *(first+3); ...
| 目录 | 
[编辑] 参数
| first, last | - |  元素的范围总和 | 
| d_first | - |  的目标范围的开头 原文:  the beginning of the destination range | 
| op | - | 被使用的二元函数对象。 该函数的签名应当等价于: Ret fun(const Type1 &a, const Type2 &b); 签名中并不需要有 const &。 | 
| 类型要求 | ||
| - InputIt必须满足InputIterator的要求。 | ||
| - OutputIt必须满足OutputIterator的要求。 | ||
[编辑] 返回值
迭代器写入过去的最后一个元素的元素.
原文:
Iterator to the element past the last element written.
[编辑] 复杂度
究竟
(last - first) - 1应用程序的二进制运算原文:
Exactly 
(last - first) - 1 applications of the binary operation[编辑] 可能的实现
| 版本一 | 
|---|
| template<class InputIt, class OutputIt> OutputIt partial_sum(InputIt first, InputIt last, OutputIt d_first) { return std::partial_sum(first, last, d_first, std::plus<InputIt, InputIt>()); } | 
| 版本二 | 
| template<class InputIt, class OutputIt, class BinaryOperator> OutputIt partial_sum(InputIt first, InputIt last, OutputIt d_first, BinaryOperation op) { if (first == last) return d_first; typename std::iterator_traits<InputIt>::value_type sum = *first; *d_first = sum; while (++first != last) { sum = op(sum, *first); *++d_first = sum; } return ++d_first; } | 
[编辑] 示例
#include <numeric> #include <vector> #include <iostream> #include <iterator> #include <functional> int main() { std::vector<int> v = {2,2,2,2,2,2,2,2,2,2}; std::cout << "The first 10 even numbers are: "; std::partial_sum(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << '\n'; std::partial_sum(v.begin(), v.end(), v.begin(), std::multiplies<int>()); std::cout << "The first 10 powers of 2 are: "; for(auto n: v) { std::cout << n << " "; } std::cout << '\n'; }
输出:
The first 10 even numbers are: 2 4 6 8 10 12 14 16 18 20 The first 10 powers of 2 are: 2 4 8 16 32 64 128 256 512 1024
[编辑] 另请参阅
| 计算区间内相邻元素之间的差 (函数模板) | |
| 计算区间内元素的和 (函数模板) | |


