On this page
std::ranges & std::views (C++20)
Prev: std::transform | Up: algorithm_and_ranges | Next: concurrency
Rel: std::span, Ranges & Span Pipeline Tutorial
Ref: cppreference — Ranges Library
Tags: #public #prog #cpp #stdlib #ranges #tier/standard
Overview
<ranges> (C++20) introduces composable, lazy range adaptors (std::views::filter, transform, take, drop, reverse, split, zip in C++23) connected with pipe syntax (|). Views do not allocate intermediate vectors—elements are evaluated on demand as you iterate.
Notes & Pitfalls
- Lazy, non-owning pipelines (C++20): Views compose with
|and allocate zero intermediate vectors. - Never return a view over a temporary container—the view dangles once the temporary is destroyed.
Example
#include <cassert>
#include <ranges>
#include <vector>
int main() {
std::vector<int> nums{1, 2, 3, 4, 5, 6};
auto even_sq = nums
| std::views::filter([](int n) { return n % 2 == 0; })
| std::views::transform([](int n) { return n * n; });
int sum = 0;
for (int v : even_sq) sum += v;
assert(sum == 56);
}
Linked from
Related notes
- tuts/cpp/stdlib/algorithm_and_ranges Linked here; links to this page; shared tags: #cpp, #prog, #ranges, #stdlib
- tuts/cpp/stdlib/algorithm_and_ranges/transform Linked here; links to this page; shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/tutorials/ranges_and_span_data_pipeline Linked here; links to this page; shared tags: #cpp, #prog, #ranges, #tier
- tuts/cpp/stdlib/algorithm_and_ranges/find_if links to this page; shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/containers/span Linked here; shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/concurrency Linked here; shared tags: #cpp, #prog, #stdlib
- tuts/cpp/stdlib/algorithm_and_ranges/sort shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/concurrency/atomic shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/concurrency/jthread shared tags: #cpp, #prog, #stdlib, #tier
- tuts/cpp/stdlib/concurrency/mutex_and_lock_guard shared tags: #cpp, #prog, #stdlib, #tier