Standard Template Library (STL)
Ranges (C++20)
Lazy, composable range-based algorithms and views — the modern STL
Interview: Cutting-edge C++20 — shows awareness of modern idioms and pipeline-style data transformations
Ranges (C++20)
The C++20 Ranges library revolutionizes STL algorithm usage. Instead of passing begin/end iterator pairs, algorithms accept ranges directly. Views enable lazy, composable transformations — chaining operations without creating intermediate containers. Think of it as LINQ for C++.
Key Concepts
Ranges Algorithms
std::ranges::sort(v) instead of std::sort(v.begin(), v.end()). Cleaner, range-aware, and avoids iterator pair mismatches.
Views (Lazy)
views::filter, views::transform, views::take — create lazy pipelines evaluated only when iterated. Zero intermediate allocations.
Pipe Operator |
Views compose with | : v | filter(pred) | transform(fn) | take(n) — readable pipeline syntax.
Projections
Algorithms accept a projection: ranges::sort(v, {}, &Person::name) — sort by member without a custom comparator lambda.
Interview Corner
Q: What is the advantage of range views being lazy?
A: Laziness means elements are computed on demand as you iterate — no intermediate containers are created. A pipeline like v | filter(pred) | transform(fn) | take(5) doesn't allocate any vectors; it processes elements one by one until 5 are produced. This is both memory-efficient (O(1) extra space) and potentially early-terminating (doesn't process all elements if only a prefix is needed).
Common Pitfalls
- Dangling views: A view does not own its elements. If the underlying range is destroyed, the view is dangling. Never store a view longer than its source.
- Compiler support: Ranges require C++20 — ensure your compiler and standard library version support it (
-std=c++20).
Best Practices
- Prefer
std::ranges::algorithms over classic STL algorithms in new C++20 code — cleaner API with projection support. - Use views for read-only data transformations where no new container is needed — they're zero-cost until iterated.