Skip to content
Tutorials Center
My learning

Topics

C++ Reference ยท Algorithms

C++ range views: filter, transform, take, drop

Reference for C++20 std::views: filter, transform, take, drop, take_while, drop_while, reverse, keys, values, iota, split. Lazy, non-owning and composable.

A view is a lightweight, non-owning description of a sequence. It does not copy elements and does not do any work when you create it. Work happens lazily, one element at a time, while you iterate. std::views::filter(pred) yields only elements that satisfy pred; std::views::transform(f) yields f(element); take(n) yields the first n elements; drop(n) skips them.

Views live in <ranges>. Each one has a class (std::ranges::filter_view) and a range adaptor object in std::views that you actually use. Because a view only refers to the data underneath, the underlying container must outlive it and, in general, must not be changed while the view is in use.

C++
#include <ranges>
namespace rv = std::views;

for (int x : v | rv::filter([](int n) { return n % 2 == 0; })) { /* ... */ }
auto firstThree = v | rv::take(3);
auto squares = v | rv::transform([](int n) { return n * n; });

Try it

C++ filter, transform, take and drop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

C++ Lazy evaluation, iota and take_while

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Syntax

C++
std::views::all(r)                        // a view of the whole range
std::views::filter(pred)                  // elements where pred(x) is true
std::views::transform(f)                  // f(x) for each element
std::views::take(n)    std::views::drop(n)
std::views::take_while(pred)   std::views::drop_while(pred)
std::views::reverse                       // needs a bidirectional range
std::views::elements<N>   std::views::keys   std::views::values
std::views::iota(start)   std::views::iota(start, end)      // counting ranges
std::views::split(delim)  std::views::join   std::views::counted(it, n)
std::views::common        std::views::empty<T>   std::views::single(x)
Name Description
pred A callable returning something convertible to bool. It should be pure and cheap.
f A callable returning the new element value (the view yields what it returns, by value or reference).
n A count; a take(n) on a shorter range just yields everything.
delim For split: a single element or a subrange to split on.

Returns: a view object that can be iterated (and piped further). Calling begin() on a view does the work needed to reach the first element, so the first call can cost O(n) for filter and drop_while.

Errors / undefined behavior: using a view after the underlying container was destroyed or reallocated is undefined behavior. A filter_view whose predicate changes results, or modifies the elements in a way that changes the predicate's answer, is also undefined.

Usage notes

  • Lazy and one pass. Each element goes through the whole pipeline before the next one starts. Nothing is stored. To keep the result as a container use std::ranges::to (C++23).
  • Views are cheap to copy, but a stateful lambda is copied with them. filter and transform store the callable inside the view.
  • filter caches begin() so a filter view is not const-iterable: pass auto&& or by non-const reference to functions that iterate it.
  • Modifying through a view. filter, take, drop and reverse over a non-const container yield references, so for (int& x : v | rv::filter(...)) x = 0; modifies the vector. transform yields the callable's result: references if the callable returns a reference, otherwise temporaries.
  • Dangling temporaries. auto v = make_vec() | rv::filter(...) leaves the view referring to a destroyed vector. Rvalue containers are rejected for many views; keep the container in a named variable.
  • Sentinel types. take_while and iota(1) without an end have a sentinel that is not an iterator, so old algorithms that need matching begin/end types may reject them. Wrap with std::views::common, or use std::ranges algorithms.
  • Performance. Pipelines usually compile to simple loops, but each layer adds a condition or call. filter re-evaluates its predicate when iterated twice.
  • reverse, size and at. A view is sized only if the underlying range is and the adaptor preserves length (transform, take, reverse do; filter does not).
  • Names. std::views is an alias for std::ranges::views. Many people write namespace rv = std::views;.