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.
#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
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.
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
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.
filterandtransformstore the callable inside the view. filtercachesbegin()so a filter view is notconst-iterable: passauto&&or by non-const reference to functions that iterate it.- Modifying through a view.
filter,take,dropandreverseover a non-const container yield references, sofor (int& x : v | rv::filter(...)) x = 0;modifies the vector.transformyields 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_whileandiota(1)without an end have a sentinel that is not an iterator, so old algorithms that need matchingbegin/endtypes may reject them. Wrap withstd::views::common, or usestd::rangesalgorithms. - Performance. Pipelines usually compile to simple loops, but each layer adds a condition or call.
filterre-evaluates its predicate when iterated twice. reverse,sizeandat. A view issizedonly if the underlying range is and the adaptor preserves length (transform,take,reversedo;filterdoes not).- Names.
std::viewsis an alias forstd::ranges::views. Many people writenamespace rv = std::views;.