Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::views::transform — lazy range transformation

std::views::transform creates a view that computes a function's result for an element only when that element is accessed. It does not create a result container; use it directly or in a pipeline with the | operator.

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

Syntax

#include <ranges>
std::views::transform(range, callable)
range | std::views::transform(callable)

std::views::transform, declared in <ranges>, is a range adaptor that creates a std::ranges::transform_view. Both std::views::transform(range, callable) and range | std::views::transform(callable) expose transformed elements in source order, without filtering them.

Evaluation is lazy: the function is invoked when an iterator is dereferenced, not when the view is constructed. Results are not cached, so repeated access can invoke the function again. The view itself neither creates a result container nor automatically overwrites the source. However, the function can return a reference rather than a value.

The function must satisfy regular_invocable for the element reference: equivalent arguments should produce equivalent results, without modifying the arguments or the function object's own state. The result cannot have type void. Therefore, avoid call counters and mutating lambdas as transformation functions.

For a container passed as an lvalue, the view refers to that container: the container must remain alive while the view is used. References captured by the function must also remain valid. An iterator additionally depends on the view object; do not retain it after the view is destroyed.

The example changes numbers[0] after creating doubled. The result 8 4 6 demonstrates that the view reads current elements rather than storing a previously computed copy. Use compilation mode -std=c++23; the supplied sources are a rolling standard draft, not a frozen C++23 text.

Examples

#include <array>
#include <iostream>
#include <ranges>

int main() {
    std::array<int, 3> numbers{1, 2, 3};
    auto doubled = numbers | std::views::transform([](int n) {
        return n * 2;
    });

    numbers[0] = 4;
    bool first = true;
    for (int value : doubled) {
        if (!first) std::cout << ' ';
        std::cout << value;
        first = false;
    }
    std::cout << '\n';
}

Result

8 4 6

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