Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::views::filter — lazy range filtering

std::views::filter creates a lazy view of elements satisfying a predicate. It does not build a separate result container and preserves the order of selected elements.

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

Syntax

#include <ranges>
std::views::filter(range, pred)
range | std::views::filter(pred)

std::views::filter from <ranges> is a range adaptor that creates a std::ranges::filter_view. Both std::views::filter(range, pred) and range | std::views::filter(pred) select elements for which the predicate is true, without changing their order.

Filtering is lazy: matches are sought when obtaining the beginning and advancing iterators, rather than by building a result container. The underlying range must be at least an input range, and the predicate must satisfy indirect_unary_predicate for its iterator. Do not make program logic depend on the number of predicate calls.

For a container passed as an lvalue, the view refers to existing data: the container must remain alive. Also keep the view itself alive while using its iterators. The view does not protect against iterator invalidation. Do not modify a selected element through an iterator so that it stops satisfying the predicate.

For a forward range, begin() caches the first match; the view is therefore not an automatically refreshed snapshot after arbitrary data changes. The example sums the selected even numbers and should print 12 followed by a newline.

Examples

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

int main() {
    std::array<int, 6> values{1, 2, 3, 4, 5, 6};
    auto evens = values | std::views::filter([](int x) {
        return x % 2 == 0;
    });

    int sum = 0;
    for (int x : evens) {
        sum += x;
    }
    std::cout << sum << '\n';
}

Result

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