CKTIS / C++
std::inclusive_scan: inclusive prefix reductions
std::inclusive_scan writes at each position a reduction that includes the current input element and returns the result end.
Version: C++23
Syntax
template<class InputIt, class OutputIt>
constexpr OutputIt std::inclusive_scan(InputIt first, InputIt last, OutputIt result);
template<class InputIt, class OutputIt, class BinaryOp>
constexpr OutputIt std::inclusive_scan(InputIt first, InputIt last, OutputIt result, BinaryOp op);
template<class InputIt, class OutputIt, class BinaryOp, class T>
constexpr OutputIt std::inclusive_scan(InputIt first, InputIt last, OutputIt result, BinaryOp op, T init);std::inclusive_scan(first,last,result) uses std::plus<>; overloads accept a binary_op and optional init. Without init, the first output derives from the first input; with init, every prefix starts from that value. The specification’s result + K denotes the iterator advanced K positions and does not require output-iterator operator+.
For 1,2,3,4, the example writes 1,3,6,10; the returned iterator ends the four-element result, so the final comparison prints 1. result == first is permitted, enabling an in-place scan.
The operation must not modify input or result elements apart from the algorithm’s assignments and must not invalidate iterators. Generalized-sum grouping is unspecified, so a non-associative operation such as floating addition can be nondeterministic. With a standard execution policy, an uncaught element-operation exception calls std::terminate, while unavailable temporary memory for parallel execution can throw std::bad_alloc; the no-policy overload propagates an operation exception.
Examples
#include <array>
#include <iostream>
#include <numeric>
int main() {
const std::array<int, 4> input{1, 2, 3, 4};
std::array<int, 4> output{};
const auto end = std::inclusive_scan(input.begin(), input.end(), output.begin());
for (int value : output) std::cout << value << ' ';
std::cout << (end == output.end()) << '\n';
}
Result
1 3 6 10 1
std::inclusive_scan → 1 3 6 10 1