Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::reduce — reduction with unspecified ordering

std::reduce from <numeric> combines a range and an initial value into one result. It may reorder and regroup operations, so it is not a substitute for std::accumulate when evaluation order matters.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <numeric>

std::reduce(first, last);
std::reduce(first, last, init);
std::reduce(first, last, init, binary_op);
std::reduce(policy, first, last);
std::reduce(policy, first, last, init);
std::reduce(policy, first, last, init, binary_op);

std::reduce from <numeric> combines the elements of [first, last) and init into one result. The default operation is std::plus<>{}. Without init, it uses a value-initialized value of the element type; with init, it returns its type T. An empty range returns init.

Unlike std::accumulate, its operation order and grouping are unspecified, including without an execution policy and with std::execution::seq. For results independent of those changes, the operation should be associative and commutative. Subtraction and floating-point addition can produce different results. Do not rely on the order of side effects.

A custom binary_op must support result–element, element–result, result–result, and element–element pairs; every result must be convertible to T. Type T must meet the Cpp17MoveConstructible requirements. The operation must not modify input elements or invalidate iterators. The type of init determines the return type, but does not by itself guarantee that every intermediate operation uses a wider type.

Overloads without a policy require input iterators; policy overloads require forward iterators. The number of operation calls is linear in the range length. The example uses small integers without overflow: every permitted ordering produces 10, and the empty range produces 7.

Examples

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

int main() {
    const std::array<int, 4> values{1, 2, 3, 4};
    const int total = std::reduce(values.begin(), values.end(), 0);
    const int empty = std::reduce(values.begin(), values.begin(), 7);
    std::cout << total << '\n' << empty << '\n';
}

Result

10
7

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources