Module 7 · Lambdas and algorithms
7.3Ranges and views
Build pipelines over data with views and the | operator: filter, transform, take, drop, iota, reverse, enumerate, zip, chunk and split. See why views are lazy, turn a pipeline back into a container with std::ranges::to, and avoid views that dangle.
On this page
- Key terms
- In 30 seconds
- Views: a range you don’t copy
- Pipelines with |
- Lazy evaluation
- Numbers on demand: std::views::iota
- Taking, dropping and reversing
- Positions with std::views::enumerate
- Two ranges side by side: std::views::zip
- Pieces: std::views::chunk and std::views::split
- Back to a container: std::ranges::to
- Which one should I use?
- Under the hood
- Common pitfalls
- An algorithm on a temporary: std::ranges::dangling
- A view that outlives its data
- A filter view can’t be read through const&
- Try it yourself
Key terms
- range
- Anything with a
begin()and anend()you can loop over: a vector, a string, an array, or a view. - view
- A range that's cheap to copy or move because it doesn't hold a copy of the elements. Usually it refers to another range and describes a step, such as keep the good ones, to apply as you read it.
- range adaptor
- Something in
std::viewsthat makes a view from a range, such asstd::views::filter(pred). - pipeline (
|) - Range adaptors joined with
|.r | std::views::filter(f)means filterr; each|feeds the result into the next step. - lazy evaluation
- Doing work only when a result is asked for. A view computes each element when you read it, not when you create the view.
std::ranges::to<C>()- A C++23 function that copies the elements of a range into a new container of type
C, such asstd::vector. - dangling iterator
- An iterator into a container that no longer exists. Using it is undefined behavior.
std::ranges::dangling- An empty type a
std::ranges::algorithm returns instead of an iterator when you pass it a temporary container. You can't use*on it, so the mistake becomes a compile error.
The algorithms each do one whole job: sort everything, count everything. Real work is often several steps in a row: keep the reads with quality 30 or more, turn each quality into an error rate, look at the first two. With algorithms alone, every step writes a new vector. A view describes a step without copying anything, and | chains views into a pipeline that runs only as you read from it.
In 30 seconds
v | std::views::filter(pred)is a view of the elements ofvthat passpred. Nothing is copied.- Chain steps with
|:v | std::views::filter(good) | std::views::transform(f) | std::views::take(2). - Views are lazy: each element is computed when you read it.
std::ranges::to<std::vector>()collects the results into a container. - A view refers to its data. If the data is gone, the view dangles.
Views: a range you don’t copy
A range is anything you can loop over with begin() and end(). A view is a range that usually refers to another range and changes what you see as you read it. The views live in <ranges>, under std::views. std::views::filter shows only the elements that pass a predicate:
#include <print>
#include <ranges>
#include <vector>
std::vector<int> qualities = {38, 12, 40, 9, 33};
auto good = qualities | std::views::filter([](int q) { return q >= 30; });
for (int q : good) {
std::print("{} ", q);
}
std::println("");
std::println("{}", good);Output
38 40 33 [38, 40, 33]
good holds no elements. It knows where qualities is and which test to apply, and it reads from qualities when you loop over it. std::println("{}", good) prints a view the same way it prints a vector.
Pipelines with |
Each | takes the range on its left and feeds it to the step on its right. std::views::transform(f) shows f(x) for each element x; std::views::take(n) stops after the first n:
#include <cmath>
#include <print>
#include <ranges>
#include <vector>
std::vector<int> qualities = {38, 12, 40, 9, 33};
auto error_rates =
qualities | std::views::filter([](int q) { return q >= 30; }) |
std::views::transform([](int q) { return std::pow(10.0, -q / 10.0); }) |
std::views::take(2);
std::println("{::.5f}", error_rates);Output
[0.00016, 0.00010]
{::.5f} prints each element with five digits after the point. Read a pipeline from left to right: start with the qualities, keep the good ones, turn each into an error rate, take two. No vector was made for any step.
Lazy evaluation
A view does no work when you create it. It computes each element at the moment you read it, and goes only as far as you read. Lambdas that print show the order:
#include <print>
#include <ranges>
#include <vector>
int main() {
std::vector<int> qualities = {12, 38, 40, 9, 33};
auto doubled = qualities | std::views::transform([](int q) {
std::println(" doubling {}", q);
return q * 2;
});
std::println("view built");
for (int d : doubled | std::views::take(2)) {
std::println("got {}", d);
}
}Output
view built doubling 12 got 24 doubling 38 got 76
Nothing ran when doubled was made. Each element was doubled just before the loop used it, and take(2) stopped the loop before 40, 9 and 33 were touched. This is called lazy evaluation. It’s why a pipeline can end with take(2) over a huge input and still do only a little work.
Numbers on demand: std::views::iota
std::views::iota(first, last) makes the numbers from first up to, but not including, last: a half-open range, like begin() and end(). With only first, it counts up with no end, which is fine because a view only makes the numbers you read:
#include <print>
#include <ranges>
std::println("{}", std::views::iota(1, 6));
std::println("{}", std::views::iota(0) | std::views::take(4));Output
[1, 2, 3, 4, 5] [0, 1, 2, 3]
Taking, dropping and reversing
std::views::drop(n) skips the first n elements, and std::views::reverse reads from the back. A view of chars prints as a list of characters; the {:s} format spec prints it as text instead:
#include <print>
#include <ranges>
#include <string>
std::string seq = "GATTACA";
std::println("{}", seq | std::views::drop(2) | std::views::take(3));
std::println("{:s}", seq | std::views::reverse);Output
['T', 'T', 'A'] ACATTAG
Positions with std::views::enumerate
std::views::enumerate (C++23) pairs each element with its position, starting at 0. A structured binding gives the two parts names:
#include <print>
#include <ranges>
#include <string>
std::string seq = "GANTNC";
for (auto [i, base] : seq | std::views::enumerate) {
if (base == 'N') {
std::println("unknown base at {}", i);
}
}Output
unknown base at 2 unknown base at 4
Two ranges side by side: std::views::zip
std::views::zip(a, b) (C++23) walks two ranges together and gives you one element from each at every step. It stops at the end of the shorter one:
#include <print>
#include <ranges>
#include <string>
#include <vector>
std::vector<std::string> ids = {"r1", "r2", "r3"};
std::vector<int> qualities = {31, 12, 38};
for (auto [id, q] : std::views::zip(ids, qualities)) {
std::println("{} {}", id, q);
}Output
r1 31 r2 12 r3 38
Pieces: std::views::chunk and std::views::split
std::views::chunk(n) (C++23) cuts a range into pieces of n elements; the last piece may be shorter. Cutting a coding sequence into codons of three bases takes one step. {::s} prints each piece as text:
#include <print>
#include <ranges>
#include <string>
std::string seq = "ATGGCCTAA";
std::println("{::s}", seq | std::views::chunk(3));Output
[ATG, GCC, TAA]
std::views::split(sep) cuts a range at each sep, which splits a line of comma-separated fields. Each piece is a range of characters; std::string_view(field) turns it into text without copying:
#include <print>
#include <ranges>
#include <string_view>
std::string_view line = "chr1,1000,A,G";
for (auto field : line | std::views::split(',')) {
std::print("[{}] ", std::string_view(field));
}
std::println("");Output
[chr1] [1000] [A] [G]
Back to a container: std::ranges::to
A view doesn’t store results. When you need them stored, to keep them after the data changes or to pass them to code that wants a std::vector, end the pipeline with std::ranges::to<C>() (C++23). It reads the view once and copies every element into a new container:
#include <print>
#include <ranges>
#include <string>
#include <vector>
std::vector<int> qualities = {38, 12, 40, 9, 33};
auto good = qualities | std::views::filter([](int q) { return q >= 30; }) |
std::ranges::to<std::vector>();
std::string seq = "GATTACA";
auto backwards = seq | std::views::reverse | std::ranges::to<std::string>();
std::println("{} {}", good, backwards);Output
[38, 40, 33] ACATTAG
std::ranges::to<std::vector>() works out the element type, int, by itself. good is a real std::vector<int> that owns its elements.
Modern C++C++23 filled in the gaps
C++20 brought views and |. C++23 added enumerate, zip, chunk, std::ranges::to and printing ranges with std::println. Every example here builds with GCC 15 and Clang 21 using GCC’s standard library. Older compilers may lack some of them.
Which one should I use?
| What | When | Why | How |
|---|---|---|---|
| An algorithm | One whole job on a container: sort, find, count, sum. | Clear, and it changes or reads the container directly. | std::ranges::sort(v) |
| A view pipeline | Several steps in a row, or only part of the data needed. | No temporary vectors, and take stops the work early. | v | std::views::filter(f) | std::views::take(5) |
std::ranges::to | You need to keep the results, read them several times, or pass a container on. | The result owns its elements and no longer depends on the input. | … | std::ranges::to<std::vector>() |
| A hand-written loop | The steps need state from earlier elements, or several results at once. | Clearer than a pipeline bent out of shape. | for (const auto& r : reads) { … } |
Rule of thumb: use a view pipeline to read data on the way through, and std::ranges::to at the end when you need to keep what comes out.
Under the hood
A view is a small object. A view of a named vector holds a pointer to it, plus whatever its step needs. With GCC’s standard library, on this platform, a view of a vector is 8 bytes (one pointer). A take view adds its count. A filter view adds the spot where it remembers its first passing element (the last pitfall explains why); its lambda captures nothing, so it takes no space. Both are 16 bytes, however many elements the vector holds:
#include <print>
#include <ranges>
#include <vector>
std::vector<int> qualities = {38, 12, 40, 9, 33};
auto all = std::views::all(qualities);
auto good = qualities | std::views::filter([](int q) { return q >= 30; });
auto first_two = qualities | std::views::take(2);
std::println("{} {} {}", sizeof(all), sizeof(good), sizeof(first_two));Output
8 16 16
std::views::all(v) is the plain view of a whole container; | wraps a container in it for you. Reading a view calls the same * and ++ on the container’s iterators that a hand-written loop would, so after optimization a pipeline often runs about as fast as the loop.
A view doesn’t store the elements it computes, so every pass over it does the work again. Two loops over a transform view call its lambda twice per element:
#include <print>
#include <ranges>
#include <vector>
std::vector<int> qualities = {38, 12, 40, 9, 33};
int calls = 0;
auto doubled = qualities | std::views::transform([&calls](int q) {
++calls;
return q * 2;
});
int total = 0;
for (int d : doubled) {
total += d;
}
for (int d : doubled) {
total += d;
}
std::println("{} calls", calls);Output
10 calls
PerformanceCollect once if you read many times
If a step is expensive and you read the results more than once, end the pipeline with std::ranges::to<std::vector>() and loop over the vector. You pay for the copy once instead of redoing the work on every pass.
Common pitfalls
An algorithm on a temporary: std::ranges::dangling
load_scores() returns a temporary vector, destroyed at the end of the statement. An iterator into it would dangle at once, so a std::ranges:: algorithm given a temporary container returns std::ranges::dangling instead, a type with no *. The mistake becomes a compile error:
#include <algorithm>
#include <print>
#include <vector>
std::vector<int> load_scores() {
return {38, 12, 40, 9, 33};
}
int main() {
auto best = std::ranges::max_element(load_scores());
std::println("{}", *best);
}The compiler rejects this
main.cpp: In function ‘int main()’:
main.cpp:11:24: error: no match for ‘operator*’ (operand type is ‘std::ranges::dangling’)
11 | std::println("{}", *best);
| ^~~~~Store the vector in a variable first, so it outlives the iterator:
#include <algorithm>
#include <print>
#include <vector>
std::vector<int> load_scores() {
return {38, 12, 40, 9, 33};
}
int main() {
auto scores = load_scores();
auto best = std::ranges::max_element(scores);
std::println("{}", *best);
}Output
40
Piping a temporary container into a view is fine: load_scores() | std::views::filter(f) moves the vector into the view, which then owns it.
A view that outlives its data
A view of a named container only refers to it. Here good_scores takes a const reference, so load_scores()’s temporary vector is destroyed at the end of the line that calls it. The view in good still points at it. Neither compiler warns; AddressSanitizer catches the read here:
#include <print>
#include <ranges>
#include <vector>
std::vector<int> load_scores() {
return {38, 12, 40, 9, 33};
}
auto good_scores(const std::vector<int>& scores) {
return scores | std::views::filter([](int s) { return s >= 30; });
}
int main() {
auto good = good_scores(load_scores());
for (int s : good) {
std::println("{}", s);
}
}This fails when it runs
ERROR: AddressSanitizer: stack-use-after-scope on address 0x…
READ of size 8 at 0x… thread T0
#0 __gnu_cxx::__normal_iterator<int const*, std::vector<int, std::allocator<int> > >::__normal_iterator(int const* const&)
… 5 frames inside the standard library
#6 main main.cpp:15
Address 0x… is located in stack of thread T0 at offset 200 in frame
#0 main main.cpp:13
This frame has 6 object(s):
[48, 52) 's' (line 15)
[64, 80) 'good' (line 14)
[96, 112) '__for_begin' (line 15)
[128, 144) '__for_end' (line 15)
[160, 176) '<unknown>'
[192, 216) '<unknown>' <== Memory access at offset 200 is inside this variable
(longjmp and C++ exceptions *are* supported)
SUMMARY: AddressSanitizer: stack-use-after-scope main.cpp:15 in mainKeep the data in a variable that lives as long as the view: auto scores = load_scores(); then auto good = good_scores(scores);. Or return std::ranges::to<std::vector>() from the function so it hands back data, not a view.
A filter view can’t be read through const&
A filter view remembers where its first passing element is after the first search, so that later calls to begin() are fast. The standard requires this, so begin() changes the view and isn’t const. A function that takes the view by const auto& can’t loop over it:
#include <print>
#include <ranges>
#include <vector>
void show(const auto& values) {
for (int v : values) {
std::print("{} ", v);
}
std::println("");
}
int main() {
std::vector<int> qualities = {38, 12, 40};
show(qualities | std::views::filter([](int q) { return q >= 30; }));
}The compiler rejects this
main.cpp: In instantiation of ‘void show(const auto:55&) [with auto:55 = std::ranges::filter_view<std::ranges::ref_view<std::vector<int> >, main()::<lambda(int)> >]’:
main.cpp:14:9: required from here
14 | show(qualities | std::views::filter([](int q) { return q >= 30; }));
| ~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
main.cpp:6:5: error: passing ‘const std::ranges::filter_view<std::ranges::ref_view<std::vector<int> >, main()::<lambda(int)> >’ as ‘this’ argument discards qualifiers [-fpermissive]
6 | for (int v : values) {
| ^~~
In file included from main.cpp:2:
/usr/include/c++/15/ranges:1832:7: note: in call to ‘constexpr std::ranges::filter_view<_Vp, _Pred>::_Iterator std::ranges::filter_view<_Vp, _Pred>::begin() [with _Vp = std::ranges::ref_view<std::vector<int> >; _Pred = main()::<lambda(int)>]’
| begin()
| ^~~~~
compilation terminated due to -fmax-errors=1.Views are small and cheap to copy, so take them by value: void show(auto values).
Try it yourself
Try it yourself
The reverse complement of a DNA sequence is the sequence read backwards with each base swapped for its partner (A↔T, G↔C). This program builds it with an index loop. Replace the loop with one pipeline that ends in std::ranges::to<std::string>().
#include <print>
#include <string>
char complement(char base) {
switch (base) {
case 'A':
return 'T';
case 'T':
return 'A';
case 'G':
return 'C';
default:
return 'G';
}
}
int main() {
std::string seq = "GATTACA";
std::string result;
for (std::size_t i = seq.size(); i > 0; --i) {
result += complement(seq[i - 1]);
}
std::println("{}", result);
}Expected output
TGTAATC
Show a hint
Start from seq, read it backwards with std::views::reverse, turn each base into its partner with std::views::transform(complement), and collect the result with std::ranges::to<std::string>().
Show a solution
#include <print>
#include <ranges>
#include <string>
char complement(char base) {
switch (base) {
case 'A':
return 'T';
case 'T':
return 'A';
case 'G':
return 'C';
default:
return 'G';
}
}
int main() {
std::string seq = "GATTACA";
auto result = seq | std::views::reverse |
std::views::transform(complement) |
std::ranges::to<std::string>();
std::println("{}", result);
}The pipeline reads seq from the back, maps each base through complement as it's read, and std::ranges::to<std::string>() copies the characters into a new string. No index arithmetic, so no off-by-one mistakes.
Saved in this browser only.