Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Ranges and views

A range exposes elements through a beginning iterator and an end sentinel. A view is a range with additional requirements that make it useful for building pipelines. The std::views::filter and std::views::transform adaptors select and transform elements without creating an intermediate result container.

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

Syntax

auto result = range | std::views::filter(predicate) | std::views::transform(function);

A range satisfying std::ranges::range provides std::ranges::begin(r) and std::ranges::end(r). The first expression yields an iterator, and the second an end sentinel; their types need not be identical. A range need not be a container or store elements.

A view satisfying std::ranges::view is a movable range recognized through enable_view, with additional operation-complexity requirements: in particular, move construction is O(1), as is copy construction when available. A view need not be copyable. Nor does view mean non-owning: some views own data, while others only refer to it.

The <ranges> header provides adaptors. Writing r | std::views::filter(pred) selects elements satisfying pred, and adding | std::views::transform(fn) transforms the selected values. This pipeline is lazy: it creates no intermediate result container; searching and transformation happen during iteration. In the example, result yields squares of the even elements of numbers, namely 4 16 36.

Here the view refers to numbers, so the array must remain alive throughout use of the view. Do not return such a pipeline referring to a local array from a function. Laziness does not mean all results are cached: another traversal can invoke the functions again, so use functions without side effects here.

The example targets compilation with -std=c++23; production runtime behavior is not attested. The supplied document is an evolving working draft, not a frozen C++23 publication; do not assume every API currently present there belongs to C++23.

Examples

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

int main() {
    std::array<int, 6> numbers{1, 2, 3, 4, 5, 6};
    auto result = numbers
        | std::views::filter([](int n) { return n % 2 == 0; })
        | std::views::transform([](int n) { return n * n; });

    bool first = true;
    for (int value : result) {
        if (!first) {
            std::cout << ' ';
        }
        first = false;
        std::cout << value;
    }
    std::cout << '\n';
}

Result

4 16 36

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