Skip to content
Tutorials Center
My learning

Topics

Lesson 110 of 171 ยท The Standard Library (STL)

Ranges and Views

Learn C++20/23 ranges - range algorithms with projections, lazy views like filter, transform, take, split, zip, enumerate and chunk, pipelines with |, and std::ranges::to.

The ranges library (C++20, greatly extended in C++23) is the biggest change to the STL since it was created. It has three parts. Range algorithms such as std::ranges::sort(v) take a whole container instead of two iterators and accept projections. Views such as std::views::filter and std::views::transform describe a sequence lazily, without copying or computing anything until you iterate. And the pipe operator | chains views into readable pipelines: numbers | std::views::filter(is_even) | std::views::transform(square). C++23 adds std::ranges::to, which turns a pipeline back into a real container.

You've used range algorithms throughout the previous lessons, from searching and sorting to modifying. This lesson explains what a range is, how views work and why they're lazy, the most useful views from C++20 and C++23 (take, drop, reverse, iota, split, zip, enumerate, chunk, slide and more), collecting results with std::ranges::to, writing your own functions that accept any range, and the lifetime pitfalls that come with views. The examples use the header <ranges> together with <algorithm>.

What is a range?

A range is anything you can call std::ranges::begin and std::ranges::end on: every standard container, C arrays, std::string, std::string_view, std::span and views. Formally, it's an iterator plus a sentinel, an end marker that may have a different type than the iterator. That generalization lets a range end at "the first zero" or "never", not just at a stored position.

Range algorithms bring three improvements over the classic ones:

  • Whole-range arguments. std::ranges::sort(v) instead of std::sort(v.begin(), v.end()), which makes mismatched iterator pairs impossible.
  • Concept checks. std::ranges::sort(my_list) fails with a short message saying std::list isn't a random-access range, instead of pages of template errors. See Concepts.
  • Projections. An extra argument applied to each element before comparing or testing: std::ranges::sort(people, {}, &Person::age).

They also protect you from one class of dangling iterators. If you pass a temporary container, an algorithm that would return an iterator into it returns std::ranges::dangling instead, and using that result doesn't compile.

C++ Range algorithms, projections and dangling

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.

Views: lazy sequences

A view is a lightweight range that refers to other data or generates elements on demand. Creating one does no work; it just stores what to do. Elements are computed one at a time, when you iterate. Views are cheap to copy, and most don't own any elements.

You create views with range adaptors in the namespace std::views (an alias for std::ranges::views). Each adaptor can be called like a function, std::views::filter(v, pred), or used with |, v | std::views::filter(pred). The pipe form reads left to right, in the order the data flows.

Adaptor Produces
views::filter(pred) only the elements where pred is true
views::transform(f) f(x) for each element
views::take(n) / views::drop(n) the first n / all but the first n
views::take_while(pred) / views::drop_while(pred) the prefix where pred holds / everything after it
views::reverse the elements backwards
views::keys / views::values the first / second member of pairs (great for maps)
views::elements<N> the Nth member of tuple-like elements
views::common a range whose iterator and sentinel types match (for older APIs)
C++ filter, transform, take and laziness

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.

The noisy part proves the laziness: "view created" prints first, then each element is transformed only when the loop asks for it, and only two elements are transformed at all, because take(2) stops the pipeline. With ordinary algorithms you'd transform all ten elements into a temporary vector and then keep two.

Because evaluation is lazy, a pipeline does one pass over the data and allocates nothing. That's often faster than a chain of std::transform and std::copy_if calls with intermediate vectors, and it's always clearer.

Range factories: iota, repeat and istream

Some views don't adapt existing data; they generate it:

  • std::views::iota(a, b) yields a, a+1, โ€ฆ, b-1. With one argument, iota(a), it counts up forever, so combine it with take or take_while.
  • std::views::repeat(x) (C++23) yields x forever, or repeat(x, n) n times.
  • std::views::single(x) and std::views::empty<T> give one or zero elements.
  • std::views::istream<T>(stream) reads values from a stream with >>.

iota is also the cleanest way to write an index loop: for (int i : std::views::iota(0, n)).

C++ iota, repeat and istream views

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++23 views: zip, enumerate, chunk, slide and friends

C++23 filled the biggest gaps in the view toolbox. These are all available in our compiler:

Adaptor Produces
views::enumerate (index, element) pairs
views::zip(a, b, ...) tuples of elements from several ranges, stopping at the shortest
views::zip_transform(f, a, b) f(a_i, b_i)
views::adjacent<N> / views::pairwise overlapping tuples of N (or 2) neighbors
views::slide(n) overlapping windows of n elements, as subranges
views::chunk(n) non-overlapping groups of n (the last one may be shorter)
views::chunk_by(pred) groups of consecutive elements where pred(prev, next) holds
views::stride(n) every nth element
views::join / views::join_with(sep) flattens a range of ranges, optionally inserting a separator
views::cartesian_product(a, b) every combination
views::as_const / views::as_rvalue read-only elements / elements to move from
C++ enumerate, zip, chunk, slide and pairwise

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.

enumerate replaces the old pattern of keeping a separate counter variable, and zip replaces index loops over parallel vectors. Note the loop that modifies prices. zip produces tuples of references as temporary values, so the structured bindings refer to the real elements and price *= 0.9 changes the vector. (That's true even with plain auto, because copying a tuple of references still gives references; auto&& is the idiomatic spelling that makes the intent obvious and works for every kind of view.)

Splitting and joining strings

std::views::split(delimiter) cuts a range into subranges at each delimiter, which may be one element or a whole sequence. Each piece is a subrange of characters; since C++23 you can construct a std::string_view (or std::string) directly from it. std::views::join_with(separator) does the reverse, and std::ranges::to<std::string>() collects the result.

C++ split, join_with and ranges::to

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.

The empty field between Oslo and Hanoi shows up as [] in the first loop: split keeps empty pieces, which is usually what you want for CSV-like data. Filter them out explicitly when you don't.

std::ranges::to: from views back to containers

Views are lazy, but at some point you usually need a real container: to store results, return them from a function, or iterate several times. std::ranges::to<Container>() (C++23) builds one from any range. It works with the pipe, accepts constructor arguments, deduces element types when you write only the template name (std::ranges::to<std::vector>()), and builds nested containers and maps from pair-like elements.

C++ Collecting with std::ranges::to

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.

std::ranges::to reserves capacity when the size is known and uses the most efficient insertion it can find, so it's as good as a hand-written loop. Before C++23, the usual workaround was std::vector<int> v(view.begin(), view.end());, which needs views::common for views whose sentinel type differs from their iterator type.

Writing functions that accept any range

To accept "anything iterable", constrain a template with a range concept. The most useful ones are std::ranges::input_range, forward_range, random_access_range and contiguous_range, plus sized_range. Helper aliases give you the element type: std::ranges::range_value_t<R>.

Take the range by forwarding reference (R&&), not by const R&. Several views, including filter and drop_while, can't be iterated when const because they cache their first position on first use.

C++ Generic functions over ranges

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.

Pitfalls and good habits

Views are powerful, but they're references in disguise, so they inherit the lifetime rules of references and iterators:

  • A view must not outlive its data. auto v = get_vector() | std::views::take(3); is fine because adapting a temporary container moves it into an owning view; but std::span, std::string_view, and views of local variables returned from a function dangle exactly like references do.
  • Don't modify elements in a way that changes a filter's answer. Writing through a filter view so that an element no longer satisfies the predicate is undefined behavior when you iterate again.
  • filter caches. The first begin() is remembered. Don't keep a filter view around while you insert into or erase from the underlying container; build a new view instead.
  • Lambdas in views capture by reference at your risk. The lambda runs later, during iteration. Captured locals must still be alive.
  • Laziness repeats work. Iterating a view twice runs the whole pipeline twice. If a transform is expensive and you need the results more than once, collect them with std::ranges::to.
  • Not every view supports everything. filter and take_while don't know their size, and split pieces are forward ranges. Collect into a vector if you need size() or random access.

A good rule: use views for local pipelines that you build and consume in the same scope, and use containers for data you store or return.

C++26 adds more views, such as std::views::concat, and C++23's std::generator (see Coroutines) lets you write your own lazy sequences as easily as a function.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does std::println("{}", std::views::iota(1, 20) | std::views::filter([](int n) { return n % 5 == 0; }) | std::views::take(2)); print?

    The filter keeps 5, 10 and 15; take(2) stops after the first two, so the output is [5, 10].
  2. 2. When does the lambda in auto v = data | std::views::transform(f); run?

    Views are lazy. Creating v only stores data and f; f runs when iteration reaches each element.
  3. 3. What does std::vector<int> a{1, 2, 3}; std::vector<char> b{'x', 'y'}; give for std::views::zip(a, b)?

    zip stops at the shortest range. Every combination would be cartesian_product.
  4. 4. Why should a generic function take a range as R&& rather than const R&?

    filter_view and similar views need to be non-const to compute and cache begin(). A forwarding reference accepts them and also containers.
  5. 5. auto words = text | std::views::split(' ') | std::ranges::to<std::vector<std::string>>(); What is words for text = "a b" (two spaces)?

    split keeps empty pieces between consecutive delimiters, so the two spaces produce an empty string in the middle.

Summary

  • A range is anything with begin and end (an iterator plus a sentinel); range algorithms take whole ranges, check concepts, accept projections and return std::ranges::dangling for iterators into temporaries.
  • Views are lazy, cheap, mostly non-owning sequences; adaptors like filter, transform, take, drop, reverse, keys and values combine with | into single-pass pipelines.
  • Factories generate data: iota (finite or infinite), repeat, single and istream.
  • C++23 adds enumerate, zip, chunk, slide, chunk_by, stride, pairwise, join_with and cartesian_product; split and join_with handle string splitting and joining.
  • std::ranges::to<Container>() (C++23) collects a pipeline into a vector, set, map, string or nested container.
  • Write generic code with range concepts and R&& parameters; remember that views refer to data they don't own, and that iterating a view twice repeats its work.

Next: Exceptions, where you'll learn how C++ reports errors with throw, try and catch, and how stack unwinding keeps your resources safe.