Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::transform_reduce — transformation and reduction

std::transform_reduce from <numeric> transforms elements of one range or corresponding pairs from two ranges, then combines the results with init. The reduction order and grouping are unspecified.

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

Syntax

std::transform_reduce(first, last, init, reduce_op, transform_op)
std::transform_reduce(first1, last1, first2, init)
std::transform_reduce(first1, last1, first2, init, reduce_op, transform_op)
// Each form also has an overload with an execution policy as its first argument.

std::transform_reduce from <numeric> returns one value of type T, deduced from init. The single-range form applies transform_op to each element of [first, last), while reduce_op combines the results and init. It does not transform init itself; an empty range yields init.

The two-range form transforms corresponding pairs of elements. The second range must contain at least as many elements as the first because its end is not passed to the function. The overload without explicit operations uses std::plus<> and std::multiplies<>, computing a dot product with init added.

Reduction may reorder and regroup values even without an execution policy: it is not a left fold like std::accumulate. For a stable result, use an associative, commutative operation and avoid overflow. Floating-point addition can produce different results due to rounding. Operations must not modify input elements or invalidate ranges. reduce_op must accept every pairing of values drawn from init and transformation results, with a result convertible to T.

The number of applications of both operations is linear in the range length. Overloads without a policy accept input iterators; execution-policy overloads require forward iterators. A policy does not guarantee a speedup or actual parallel execution.

Examples

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

int main() {
    const std::array<int, 3> a{1, 2, 3};
    const std::array<int, 3> b{4, 5, 6};

    const int result = std::transform_reduce(
        a.begin(), a.end(), b.begin(), 0);

    std::cout << result << '\n';
}

Result

32

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