Skip to main content
Be Bitwise
C++Modern C++ Patterns

Ranges and Views

C++20 ranges rewrite how you handle sequences. No more handwritten loops or iterator-pair STL calls glued together with std::back_inserter — ranges let you compose operations as a pipeline. Views are lazy: no intermediate containers, no work until somebody actually iterates.

The Problem with Traditional STL

In classic STL, even a simple transform burns through temporary containers and an iterator dance:

cpp
// Classic approach: verbose and creates temporaries
std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::vector<int> even;
std::copy_if(numbers.begin(), numbers.end(), std::back_inserter(even),
[](int n) { return n % 2 == 0; });
std::vector<int> squared;
std::transform(even.begin(), even.end(), std::back_inserter(squared),
[](int n) { return n * n; });
// squared = {4, 16, 36, 64, 100}

Ranges: The Modern Way

cpp
#include <ranges>
#include <vector>
#include <iostream>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
auto result = numbers
| std::views::filter([](int n) { return n % 2 == 0; })
| std::views::transform([](int n) { return n * n; });
for (int n : result) {
std::cout << n << " "; // 4 16 36 64 100
}
std::cout << "\n";
return 0;
}

The pipe operator | chains operations left-to-right, reading the same way you'd describe the work out loud. No vectors get allocated behind the scenes. The result is a lazy view that hands you values only when you ask for them.

Key Concept

Views are lazy. Writing numbers | filter(...) | transform(...) performs zero computation — the expression just describes one. Each element is computed on demand as you iterate, and nothing gets buffered along the way.

Here's what that on-demand pull looks like for numbers | filter(even) | transform(square) | take(2). Each request travels right to left through the pipeline, and a value only travels back once it has survived every stage. Watch for what never happens: after the second result, nobody reads 5 through 10.

Common Views

cpp
#include <ranges>
#include <vector>
#include <string>
#include <iostream>
std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
// Take the first N elements
auto first_five = v | std::views::take(5);
// 1 2 3 4 5
// Drop the first N elements
auto after_three = v | std::views::drop(3);
// 4 5 6 7 8 9 10
// Reverse
auto reversed = v | std::views::reverse;
// 10 9 8 7 6 5 4 3 2 1
// Take while predicate is true
auto small = v | std::views::take_while([](int n) { return n < 5; });
// 1 2 3 4
// Generate a range of numbers
for (int i : std::views::iota(1, 11)) {
std::cout << i << " "; // 1 2 3 4 5 6 7 8 9 10
}

Composing Transformations

Composition is where this earns its keep. Every view adapter hands back a new view, ready to feed into the next one:

cpp
#include <ranges>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
struct Student {
std::string name;
int grade;
};
int main() {
std::vector<Student> students = {
{"Alice", 92}, {"Bob", 78}, {"Carol", 95},
{"Dave", 88}, {"Eve", 73}, {"Frank", 98}
};
// Get names of students with grade >= 90, in their original order
auto honor_roll = students
| std::views::filter([](const Student& s) { return s.grade >= 90; })
| std::views::transform([](const Student& s) { return s.name; });
for (const auto& name : honor_roll) {
std::cout << name << "\n"; // Alice, Carol, Frank
}
return 0;
}

Views are Non-Owning

Views never own their data. They hold a reference to the underlying range:

cpp
std::vector<int> v = {1, 2, 3, 4, 5};
auto view = v | std::views::take(3);
v[0] = 100; // Modifying the original
for (int n : view) {
std::cout << n << " "; // 100 2 3 - view sees the change
}

One more surprise from filter: the view works out where its first match is on the first call to begin() and caches it, so begin() isn't a const member. You can't loop over a const filter view, so a function that takes one by const& can't iterate it either. Pass views by value instead; they're cheap to copy.

The source range must outlive the view. Return a view from a function that owns the underlying container and you've shipped a dangling-reference bug.

cpp
auto evens() {
std::vector<int> v = {1, 2, 3, 4, 5, 6};
return v | std::views::filter([](int n) { return n % 2 == 0; });
}
for (int n : evens()) std::cout << n << " ";
What does the loop print?

Nothing you can rely on. The view holds a reference to v, and v and its heap buffer are destroyed when evens() returns, so the loop reads freed memory. It might print 2 4 6, print garbage or crash, often with no compiler warning. AddressSanitizer will usually flag it at runtime. Return the std::vector itself, or build the view in the caller over a container the caller owns.

Materializing Views into Containers

When you need the results to stick around, copy them into a container:

cpp
#include <ranges>
#include <vector>
#include <algorithm>
auto view = std::views::iota(1, 101)
| std::views::filter([](int n) { return n % 3 == 0; });
// C++20: build the vector from the view's iterators
std::vector<int> result(std::ranges::begin(view),
std::ranges::end(view));
// C++23: say it in one step
auto result23 = view | std::ranges::to<std::vector>();

Range Algorithms

std::ranges:: versions of algorithms work directly with ranges:

cpp
#include <ranges>
#include <algorithm>
#include <vector>
#include <iostream>
std::vector<int> v = {5, 3, 1, 4, 2};
// Sort (modifying)
std::ranges::sort(v);
// Find
auto it = std::ranges::find(v, 3);
// Any/All/None
bool any_even = std::ranges::any_of(v, [](int n) { return n % 2 == 0; });
// Min/Max
auto [min, max] = std::ranges::minmax(v);
std::cout << "Min: " << min << " Max: " << max << "\n";
// Count
auto count = std::ranges::count_if(v, [](int n) { return n > 3; });

Projection

Range algorithms accept projections — a function run on each element before the comparison fires:

cpp
struct Person {
std::string name;
int age;
};
std::vector<Person> people = {
{"Alice", 30}, {"Bob", 25}, {"Carol", 35}
};
// Sort by age using projection
std::ranges::sort(people, {}, &Person::age);
// Equivalent to: sort by comparing p.age for each element
// Find youngest
auto youngest = std::ranges::min(people, {}, &Person::age);
std::cout << youngest.name << "\n"; // Bob

String Processing with Views

cpp
#include <ranges>
#include <string>
#include <string_view>
#include <iostream>
std::string csv_line = "hello,world,foo,bar";
// Split by delimiter (views::split is C++20)
for (auto word : csv_line | std::views::split(',')) {
// Each piece is a subrange; the iterator-pair constructor works in C++20
std::cout << std::string_view(word.begin(), word.end()) << "\n";
}

C++23 lets you write std::string_view(word) directly, because that's when string_view gained a constructor from a contiguous range.

Performance Benefits

Because views are lazy:

  • No intermediate allocations: Each element flows through the entire pipeline
  • Early termination: take(5) on a filtered view stops after 5 matches
  • One pass over the data: Each element goes through every stage while it's still in a register or cache, instead of the whole range being walked once per stage

None of that is free in every build. Views lean on the optimiser to inline away layers of iterator wrappers, and at -O0 a pipeline is often slower than the plain loop. Measure an optimised build before you claim a speed-up either way.

cpp
// Only processes elements until 3 matches are found
auto first_three_evens = numbers
| std::views::filter([](int n) { return n % 2 == 0; })
| std::views::take(3);

The runner on this site compiles C++14, so there's no <ranges> to play with, but you can still count the work. This puts the eager STL version from the top of the lesson next to the loop a filter | transform | take(3) pipeline effectively runs. Predict both pairs of counts before you run it.

Try itAsk for the first 300 results instead of 3 and see how the gap between the two approaches shrinks.
C++ (GCC 9.2.0)

Ranges nudge C++ programmers away from imperative loops toward declarative pipelines. Once it clicks, you stop reaching for the old <algorithm> boilerplate.