Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::exclusive_scan: prefixes excluding the current element

std::exclusive_scan writes, for every position, a reduction of the initial value and earlier elements, excluding the element at that position.

Version: C++23

Syntax

template<class InputIterator, class OutputIterator, class T, class BinaryOperation>
constexpr OutputIterator exclusive_scan(
    InputIterator first, InputIterator last, OutputIterator result,
    T init, BinaryOperation binary_op);

std::exclusive_scan(first, last, result, init, binary_op) from <numeric> writes N results and returns the output iterator advanced by N positions. For nonempty input the first result is init, and position K includes only elements before K; the overload without an operator uses std::plus<>.

For {3, 1, 4} with init = 10, the example produces {10, 13, 14}. Positional notation in the specification does not require operator+ from the sequential iterators: suitable input and output iterators plus space for N results are enough.

T must be move-constructible, the required binary_op calls must produce values convertible to T, and the operation must neither modify the processed ranges nor invalidate iterators. result may equal first; do not rely on other overlap. Grouping can vary, so a non-associative operation can be nondeterministic. In the displayed no-policy overload, an exception from binary_op propagates normally. In an overload invoked with a standard execution policy, an uncaught exception from an element operation calls std::terminate; failure to allocate temporary memory during parallel execution can throw std::bad_alloc.

Examples

#include <array>
#include <iostream>
#include <numeric>

int main() {
    const std::array input{3, 1, 4};
    std::array<int, 3> output{};
    std::exclusive_scan(input.begin(), input.end(), output.begin(), 10);
    std::cout << output[0] << ' ' << output[1] << ' ' << output[2] << '\n';
}

Result

10 13 14

std::exclusive_scan → 10 13 14

Sources