skip to content

In C++20, what does readings | std::views::filter(f) | std::views::transform(g) | std::views::take(2) build, and when does f run?

level: juniorimportance: should knowfreq 50%

answer

  1. a view, not a container
  2. nothing runs at construction
  3. work happens per iteration
  4. one element at a time
  5. take stops the loop

basics

~20 s

It builds a lazy view that refers to readings and stores f, g and the count; nothing is examined yet. f and g run only while something iterates the view, one element at a time, until take has yielded two.

solid answer

~40 s

In C++20 `<ranges>`, `views::filter`, `views::transform` and `views::take` are **range adaptors**, and `|` composes them left to right: `readings | views::filter(f)` is the same as `views::filter(readings, f)`. The result is a nested view type - roughly `take_view<transform_view<filter_view<ref_view<vector<Reading>>, F>, G>>` - holding a reference to `readings` and the callables. Building it does no work: `f` and `g` run only while a range-for loop or an algorithm iterates it. Each step pulls one element through the chain: the filter calls `f` on elements until one passes, the transform applies `g` when that element is read, and `take` counts. There is no intermediate vector. Because the view refers to `readings`, the vector must outlive it, and anything changed in `readings` before iteration is what the view sees.

code

cpp · 22 lines
cpp
#include <iostream>
#include <ranges>
#include <vector>

struct Reading {
    int sensorId;
    double celsius;
};

int main() {
    std::vector<Reading> readings{{1, 21.5}, {2, 98.0}, {3, 22.1}, {4, 97.4}, {5, 99.9}};

    auto hot = readings
             | std::views::filter([](const Reading& r) {
                   std::cout << "check " << r.sensorId << '\n';
                   return r.celsius > 90.0; })
             | std::views::transform([](const Reading& r) { return r.sensorId; })
             | std::views::take(2);
    std::cout << "pipeline built\n";            // nothing has run yet

    for (int id : hot) std::cout << "alert " << id << '\n';
}

go deeper

for a junior

Know that a views pipeline builds a lazy object, that | composes adaptors left to right, and that nothing runs until you loop over it.

for a middle

Explain pull-based iteration through nested views, why no intermediate containers exist, and that the view refers to its source rather than owning it.

for a senior

Anticipate repeated work on re-iteration, side effects running at loop time, and filters scanning ahead under take.

for a principal

Decide where lazy pipelines improve clarity and where a materialised container is easier to reason about, and write that down for the team.

## Adaptors, views and the pipe C++20 added `<ranges>` with two kinds of building blocks: - **Views** - lightweight ranges such as `std::ranges::filter_view` that refer to other ranges instead of owning copies of their elements. - **Range adaptor objects** in `std::views` (an alias for `std::ranges::views`) - `views::filter`, `views::transform`, `views::take`, `views::iota` and more - that create those views. An adaptor can be called directly, `std::views::filter(readings, f)`, or applied with the **pipe** operator: `readings | std::views::filter(f)`. The two are equivalent; the pipe exists so that a chain reads left to right in the order the data flows: ```cpp auto hot = readings | std::views::filter([](const Reading& r) { return r.celsius > 90.0; }) | std::views::transform([](const Reading& r) { return r.sensorId; }) | std::views::take(2); ``` ## What the variable holds `hot` is not a list of sensor ids. Its type is a nest of view templates, approximately `take_view<transform_view<filter_view<ref_view<std::vector<Reading>>, F>, G>>`. It stores: - a reference to `readings` (through `ref_view`, because `readings` is an lvalue); - copies of the two lambdas; - the count, 2. Creating it allocates nothing and calls neither lambda. That is what **lazy** means here: the description of the computation is separate from running it. ## When the work happens Work happens when something iterates the view - a range-for loop, a `std::ranges` algorithm, or a conversion into a container. Iteration is **pull-based**, one element at a time: 1. `begin()` on the take view asks the transform view, which asks the filter view, which calls `f` on elements of `readings` until one passes. 2. Dereferencing the iterator applies `g` to that element and yields the sensor id. 3. Incrementing asks the filter for the next passing element, calling `f` again. 4. `take` counts the elements it has handed out and reports the end after the second one. In the example below the output is `pipeline built` first, then `check` lines interleaved with `alert` lines: each element is filtered, transformed and consumed before the next one is examined. No temporary vector of hot readings or of ids is ever created, which is the main practical benefit - one pass, no allocation. ## Consequences you must design for | Fact | Consequence | |---|---| | The view refers to `readings` | `readings` must outlive `hot`; returning `hot` from a function that owns `readings` dangles | | Work is deferred | changes to `readings` before the loop are visible; side effects in `f` happen during iteration, not at construction | | Iterating twice repeats the work | `f` and `g` run again on a second loop, except where a view caches something | | The type is unnamed in practice | use `auto`, or a concept such as `std::ranges::input_range auto` for parameters | ## A note on take and filter `take(2)` limits how many elements the loop *receives*, but the loop still increments the iterator after receiving the second one. With a filter underneath, that increment searches for the next passing element. In the example, `check 5` is printed after `alert 4`, even though no third alert is produced. Put cheap predicates in filters that sit below a `take`, or put the `take` first when the limit applies to raw readings rather than to matches. ## Adaptor arguments and closures Each adaptor called with only its extra arguments - `std::views::filter(pred)`, `std::views::take(2)` - returns a **range adaptor closure object**: a partial application waiting for the range. Two closures can be combined before any range is involved: ```cpp auto hotIds = std::views::filter(isHot) | std::views::transform(toId); auto firstTwo = readings | hotIds | std::views::take(2); ``` This lets a team name a reusable stage once and apply it to several sources. The closure stores copies of its arguments, so a lambda that captures by reference must not outlive what it captures - the same rule as for any stored lambda. Some adaptors are not lazy filters of an existing range but **factories** that create one: `std::views::iota(1, 6)` yields 1 to 5 on demand, and `std::views::iota(0)` counts forever, which is only safe with a `take` or another bound downstream. A factory plus `take` is the idiomatic way to write "the first N of something infinite" without a counter variable. ## When to reach for it Use a pipeline when you want to express filter-map-limit over existing data without temporary containers, and when the result is consumed once, close to where it is built. When the result must be stored, returned or iterated many times, materialise it into a container.

  • What happens if you iterate the same filter-transform-take view twice?
    The work runs again: the filter calls its predicate and the transform calls its function a second time, because a view stores the recipe, not results. The one exception in this chain is that `filter_view` caches the iterator to its first matching element after the first `begin()` call, so the scan to the first match is not repeated. If the results are needed repeatedly, materialise them into a container once.
  • Why can you not return such a pipeline from a function that builds it over a local std::vector?
    Built from an lvalue, the pipeline holds a `ref_view` - effectively a pointer - to the local vector. When the function returns, the vector is destroyed and the view refers to a dead object, so iterating it is undefined behaviour. Either return a container, or move the vector into the pipeline (`std::move(local) | views::filter(f)`), which creates an `owning_view` that keeps the data alive.

  • Saying the pipeline computes a filtered vector when it is declared
  • Believing views copy the elements of the source container
  • Expecting the predicate to run exactly once per element on every pass
  • Assuming take stops the filter from looking any further
  • Returning a view over a local container from a function

Assumes C++23; <ranges>, its views and the pipe syntax were added in C++20.