std::partial_sum

Header: <numeric>

  1. If [first,last) is empty, does nothing.

# Declarations

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

(constexpr since C++20)

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

(constexpr since C++20)

# Parameters

# Return value

Iterator to the element past the last element written, or d_first if [first,last) is empty.

# Notes

acc was introduced because of the resolution of LWG issue 539. The reason of using acc rather than directly summing up the results (i.e. *(d_first + 2) = (*first + *(first + 1)) + *(first + 2);) is because the semantic of the latter is confusing if the following types mismatch:

acc serves as the intermediate object to store and provide the values for each step of the computation:

# Example

#include <functional>
#include <iostream>
#include <iterator>
#include <numeric>
#include <vector>
 
int main()
{
    std::vector<int> v(10, 2); // v = {2, 2, 2, 2, 2, 2, 2, 2, 2, 2}
 
    std::cout << "The first " << v.size() << " even numbers are: ";
    // write the result to the cout stream
    std::partial_sum(v.cbegin(), v.cend(), 
                     std::ostream_iterator<int>(std::cout, " "));
    std::cout << '\n';
 
    // write the result back to the vector v
    std::partial_sum(v.cbegin(), v.cend(),
                     v.begin(), std::multiplies<int>());
 
    std::cout << "The first " << v.size() << " powers of 2 are: ";
    for (int n : v)
        std::cout << n << ' ';
    std::cout << '\n';
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 242C++98op could not have side effectsit cannot modify the ranges involved
LWG 539C++98the type requirements needed for the resultevaluations and assignments to be valid were missingadded

# See also