Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::transform — transforming range elements

std::transform from <algorithm> writes the results of a unary or binary operation into an output range. It neither creates a container nor automatically increases its size.

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

Syntax

#include <algorithm>
std::transform(first1, last1, result, op);
std::transform(first1, last1, first2, result, binary_op);

std::transform from <algorithm> processes the half-open range [first1, last1). The unary form applies op to each element; the binary form applies binary_op to corresponding elements from two ranges. It writes results starting at result and returns the iterator past the last element written.

For N elements in the first range, it performs exactly N operation calls. The classic binary form accepts no end iterator for the second range: that range must contain at least N accessible elements. The output must also support N writes. Calling reserve() alone does not create elements; writing through begin() requires a suitably sized container.

In-place transformation is permitted when result == first1 or, for the binary form, result == first2. The operation itself must not modify elements of the processed ranges or invalidate iterators. Do not depend on its invocation order; returning a result without side effects is the simplest approach.

The example demonstrates both forms without an execution policy. This entry targets C++23; the supplied standard draft is a living document and also contains later extensions that the example does not use.

Examples

#include <algorithm>
#include <array>
#include <iostream>

int main() {
    const std::array<int, 3> input{1, 2, 3};
    std::array<int, 3> squared{};
    std::array<int, 3> sums{};

    std::transform(input.begin(), input.end(), squared.begin(),
                   [](int x) { return x * x; });
    std::transform(input.begin(), input.end(), squared.begin(), sums.begin(),
                   [](int x, int y) { return x + y; });

    std::cout << squared[0] << ' ' << squared[1] << ' ' << squared[2] << '\n';
    std::cout << sums[0] << ' ' << sums[1] << ' ' << sums[2] << '\n';
}

Result

1 4 9
2 6 12

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