std::vector<int> data {2, 3, 5, 7, 11, 13, 17, 19}; std::cout << "Partial sums: "; std::partial_sum(std::begin(data), std::end(data),std::ostream_iterator<int>{std::cout, " "}); std::cout << std::endl; // Partial sums: 2 5 10 17 28 41 58 77可以看到,輸出是由長度穩定增加的序列的和組成的。通過執行下面的程式碼,可以很容易展示出這些結果:
std::vector<int> data {2, 3, 5, 7, 11, 13, 17, 19}; std::cout << "Original data: "; std::copy(std::begin(data), std::end(data), std::ostream_ iterator<int>{std::cout, " "}); std::adjacent_difference(std::begin(data), std::end(data),std::begin (data)); std::cout << "nDifferences : "; std::copy(std::begin(data), std::end(data),std::ostream_iterator<int>{std::cout," "}); std::cout << "nPartial sums : "; std::partial_sum(std::begin(data), std::end(data),std::ostream_iterator<int>{std::cout, " "}); std::cout << std::endl;注意,這裡的輸出疊代器和輸入序列的開始疊代器是相同的。這是合法的,可以認為 data 是可覆蓋的,但演算法被定義為阻止這麼做。執行這段程式碼後得到的輸出如下:
Original data: 2 3 5 7 11 13 17 19
Differences: 2 1 2 2 4 2 4 2
Partial sums: 2 3 5 7 11 13 17 19
std::vector<int> data {2, 3, 5, 7, 11, 13, 17, 19}; std::cout << "Partial sums:"; std::partial_sum (std::begin (data) , std::end (data),std::ostream_iterator<int>{std::cout, " "}, std::minus<int>()); std::cout << std::endl; // Partial sums: 2 -1 -6 -13 -24 -37 -54 -73這裡使用了減法運算子,所以值是 2、2-3、2-3-5、2-3-5-7 的結果,以此類推。