CKTIS / C++
std::partial_sum — prefix sums
std::partial_sum from <numeric> writes successive prefix sums of a range. It also accepts a custom binary operation; its accumulator uses the input value type, independently of the output type.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
std::partial_sum(first, last, result);
std::partial_sum(first, last, result, binary_op);std::partial_sum from <numeric> processes [first, last) and writes one result per element. The first result is the first element; subsequent results add each following element to the accumulator in input order.
The overload accepting binary_op replaces addition with binary_op(std::move(acc), *i). The accumulator acc uses the input iterator's value type, not the output type. It must be constructible from *first, and the operation's result must be implicitly convertible to that type. A wider output type does not widen the calculation.
Provide room for every result; result == first is permitted. The custom operation must not modify elements or invalidate iterators or subranges of the input and output. The function returns the iterator past the last written result; an empty range performs no writes and returns result.
For N > 0, exactly N - 1 binary operations are performed. The example allocates four output elements and prints 2 5 9 14.
Examples
#include <array>
#include <iostream>
#include <numeric>
int main() {
const std::array<int, 4> values{2, 3, 4, 5};
std::array<int, 4> sums{};
const auto end = std::partial_sum(values.begin(), values.end(), sums.begin());
for (auto it = sums.begin(); it != end; ++it) {
if (it != sums.begin()) {
std::cout << ' ';
}
std::cout << *it;
}
std::cout << '\n';
}
Result
2 5 9 14
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.