C++ Tutorial

Ranges & Views

C++20 range library and pipeline (|) composition

What are C++ Ranges?

Introduced in C++20, Ranges are a massive update to the C++ Standard Template Library. They provide a much simpler and more powerful way to work with collections of data. Instead of passing two iterators (begin and end) to every algorithm, you can just pass the entire container once.
cpp
#include <ranges>
#include <algorithm>
#include <vector>

std::vector<int> nums = {3, 1, 4, 1, 5, 9, 2};

// One function call, no iterator begin/end pairs!
std::ranges::sort(nums);

Comparisons: Traditional Algorithm vs. Modern Range

FeatureTraditionalModern Range
LogicRequires begin() and end()Pass the whole nums object.
PipesImpossible; use nested loopsUse the `
CopyOften creates new collectionsUses "Views" (Lazy processing!)

The Power of Views (Lazy Processing)

A View doesn't modify the original collection and doesn't create a new one. It's "Lazy," meaning the work (filtering, transforming) is only done when you actually read the data!
cpp
#include <iostream>
#include <vector>
#include <ranges>

namespace views = std::views;
std::vector<int> nums = {1, 2, 3, 4, 5, 6};

// Pipe logic together!
auto results = nums 
    | views::filter([](int n) { return n % 2 == 0; }) // Take even numbers!
    | views::transform([](int n) { return n * n; })  // Square them!
    | views::take(2); // Take only the first two from the results!

// { 4, 16 }
Wait! The variables inside results aren't calculated until the for loop actually hits them! This saves a massive amount of memory and time.

Most Common Views

ViewPurposeResult
filter(f)Logic filteringKeep only values where f is true.
transform(f)Map/TransformationApply function f to all items.
take(n)Limit sizeTake the FIRST n items.
drop(n)OffsetSkip the FIRST n items.
reverseInverseIterate through the container backwards.
keys/valuesMap iterationExtract only the key or value from a map.

Summary

FeatureSyntaxBehavior
Rangestd::ranges::sort(v)Simple algorithms for whole collections
View`vviews::filter(f)`
**Pipe ()**Combine many tools
LazyOnly compute if readHigh performance and memory efficiency
Best ForData processing, filtering, functional C++
ModernC++20 required!
SafeImpossible to miss an end() iterator!
All-ofstd::ranges::all_of(v, f)Check every item in a container
Commonstd::views::allRepresent an entire container as a view
Spanstd::span (Non-owning view of a raw array!)
STLStandard algorithms are now range-compatible!
AdaptorUse `` with "Range Adaptors"
CheckUse std::ranges::range concept!
Distancestd::ranges::distance(v)
Sizestd::ranges::size(v)
Beginstd::ranges::begin(v)
SentinelConcept for the end of a range
PointerRaw arrays are technically ranges!
Stringstd::string_view (Fast, read-only string view!)
Infiniteviews::iota(1) (Generate numbers 1, 2, 3...!)
Joinviews::join (Flatten nested ranges! - C++23)
Splitviews::split (Split a range into chunks!)
Zipviews::zip (Combine multiple ranges! - C++23)
Enumerateviews::enumerate (Keep track of the index! - C++23)
PerformanceAs fast as manual code, but much safer
CompositionCombine many small operations into a powerful tool