Name

partial_sum function template — Compute sums of subranges in a range

Synopsis

template <typename InIter, typename OutIter>
OutIter partial_sum(InIter first, InIter last, OutIter result);
template <typename InIter, typename OutIter, typename BinOp>
OutIter partial_sum(InIter first, InIter last, OutIter result, BinOp binary_op);

The partial_sum function template assigns partial sums to the range that starts at result. The partial sums are computed by accumulating successively larger subranges of [first, last). Thus, the first result item is *first, the second is *first + *(first + 1), and so on. The second version calls binary_op instead of using the addition operator (+).

Technical Notes

For each i in [first, last), assign *(result + k) = sum(first, i), in which k = i - first, and sum(a, b) computes the sum in the manner of accumulate(a + 1, b, *a, binary_op).

The return value is the result iterator, pointing to one past the last item written.

The binary_op function or functor must not have any side effects. The result iterator can be the same as first.

Complexity is linear: binary_op is called exactly (last - first) - 1 times.

Get C++ In a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.