liveBook · Manning

Std::views::filter

As explained in 100 C++ Mistakes and How to Avoid Them

std::views::filter is a C++ standard-library range adaptor that lazily exposes elements satisfying a supplied predicate.

std::views::filter lazily exposes only the elements for which a supplied predicate returns true. A predicate returns a Boolean: true retains an element, while false rejects it. section 4.4

Use it in a ranges pipeline to compose filtering with transformations. The resulting view can be traversed with begin() and end(), but std::accumulate still consumes iterator pairs rather than composing directly as a range operation. section 4.4

Filter transformed values

auto evens = vals | std::views::transform([](int x) { return abs(x); }) | std::views::filter([](int x) { return x % 2 == 0; }); auto sum = std::accumulate(evens.begin(), evens.end(), 0);

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Defines predicate-based inclusion and demonstrates composition, but stops short of a fully composable accumulation adapter.
Examples
Filters absolute values to retain even numbers, then sums them with std::accumulate.
What it assumes
Assumes value sequences and containers while defining predicates and range-adapter filtering through examples.
What you can do after
Apply it via std::views::filter to compose predicate-based selection with transformations and iterator-based reduction.
How it connects
Connects ranges, range adapters, predicates, std::views::transform, std::accumulate, and lambdas.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.