C++ Ranges: from your first pipeline to production-ready reasoning
Modern C++ · Learn by doing
You wrote three operations. When do they actually happen?
Small challenges to move from “looks neat” to “I know what this code does.”
You have a list of request latencies. Select the slow ones, convert the unit and display a few samples. A for loop works. So do two intermediate vectors. Soon, a simple rule disappears behind the machinery of iterating, checking and copying.
Ranges put that rule in front of the reader. The elegant code brings less photogenic questions, though: who owns the data? Does the result exist yet? Can I sort this? Why did swapping two lines change the answer?
We will answer with code you can change. If templates still sound like a conversation in another language, that is fine: the first experiment only needs a vector, a loop and a small function. If you already use ranges, pay attention to lifetimes and iterator categories. That is where things get interesting.
How to use this bench
Section titled “How to use this bench”Read the question and fill a blank, choose an output or arrange the operations. Select Check answer for an explanation. Hints appear one at a time; Start again clears your attempt. Everything happens here, without opening another tool.
Checks are local and educational: they recognize the answers defined for each task, without compiling C++ or executing your input. An unrecognized variation may still be valid C++; in that case, use the requested simple form. Your answer is not sent to a server.
The complete report at the end is still available to download if you want to experiment with a C++20 toolchain. Compilation checks language rules; tests help check behavior.
1. Range, algorithm and view: three different pieces
Section titled “1. Range, algorithm and view: three different pieces”A range supplies a beginning and an end for traversing elements. A vector is a range; so is an array. More precisely, the beginning provides an iterator and the end can provide a sentinel, which tells iteration when to stop. Their types need not match. Standard definition.
An algorithm performs work: std::ranges::sort(values) sorts; std::ranges::find(values, 42) searches. Many algorithms accept the whole range without making you spell out begin() and end().
A view is a range with specific requirements that support efficient composition. Think of it as a way of presenting or traversing data. filter selects, transform computes the presented value and take limits the count. A view may reference data or own its base: “views never own anything” is an incorrect shortcut. View requirements · owning_view.
For now, keep this distinction: std::ranges contains algorithms and infrastructure; std::views provides view adaptors. A transformation in std::views has a different contract from an algorithm that writes results to a destination.
2. First pipeline: make the rule readable
Section titled “2. First pipeline: make the rule readable”The | operator chains adaptors. Read left to right: take the latencies, keep those of at least 30 ms, convert to microseconds. This use of | does not create a thread or an operating-system process pipe.
[](int ms) { return ms >= 30; } is a lambda: a small function. Empty brackets mean it captures no outside variables. auto asks the compiler to deduce the composed view’s type — saving a type declaration nobody would miss writing.
Experiment 1 — complete the rule
Section titled “Experiment 1 — complete the rule”The latencies are 8, 45, 12, 90, 30, 5. Complete the filter condition. After selecting values, a transformation can convert milliseconds to microseconds with std::views::transform([](int ms) { return ms * 1000; }).
Selection and transformation happen as the for loop consumes the view. We did not construct one vector for filtered values and another for converted values. This does not mean every adaptor does absolutely nothing during construction; it means these results are produced on demand. filter_view · transform_view.
3. Order changes meaning
Section titled “3. Order changes meaning”“The first two even numbers” and “the even numbers among the first two numbers” ask different questions. The pipeline follows the question you wrote, even when it is not the one you had in mind.
Experiment 2 — arrange the operations
Section titled “Experiment 2 — arrange the operations”If your prediction was wrong, this is a good place to be wrong: six numbers, one rule, no production incident. Explain the difference in one sentence before moving on. If you can explain it, you are already moving beyond memorizing syntax.
Order also matters with generated sequences:
auto first_five = std::views::iota(1) | std::views::filter([](int n) { return n % 2 == 0; }) | std::views::take(5); // 2, 4, 6, 8, 10iota(1) has no explicit final bound. We stop early here, with values that fit in int. Do not generalize that into “infinite integers”: the types still have limits. And take(5) does not guarantee bounded time if the filter never produces five results. When your domain must be finite, use a bounded source such as iota(1, 100). iota specification.
4. Lazy evaluation is not a snapshot
Section titled “4. Lazy evaluation is not a snapshot”A view over an existing vector generally observes that vector. It does not automatically represent “the values when I wrote auto”. To keep an independent result, materialize it in an object that owns those values.
Experiment 3 — view versus snapshot
Section titled “Experiment 3 — view versus snapshot”Lazy does not mean memoized. Traversing a transform again may repeat its calculation. For expensive transformations consumed several times, materializing can be the better choice. Keep predicates and transformations stable, without depending on mutable counters or “how many times the lambda ran”. Their contracts include semantic requirements the compiler cannot check for you. regular_invocable.
Another detail: filter_view can cache its initial matching position over a multipass base. Do not treat a filtered view as a reactive query that recomputes everything after every edit. Avoid changing the base’s structure or membership conditions during use; when needed, finish traversal and construct a fresh view. begin and caching rules.
5. Lifetimes: who keeps everything alive?
Section titled “5. Lifetimes: who keeps everything alive?”Consider this function. Incorrect example; do not iterate the returned view:
auto broken() { std::vector<int> values{10, 20, 30}; return values | std::views::filter([](int n) { return n >= 20; });} // values is gone; the returned view refers to destroyed dataThe function may compile. That does not resurrect the vector. An auto return type does not solve ownership.
There are three approaches: accept a source whose lifetime the caller guarantees; return a materialized container; or transfer ownership of the source into the view. On current implementations with the C++20 correction for temporary ranges, the last option can look like this:
auto owned(int minimum) { return std::vector<int>{10, 20, 30} | std::views::filter([minimum](int n) { return n >= minimum; });}The composition owns the temporary base. minimum is captured by value, too. Capturing it by reference would introduce another broken lifetime: the local parameter ends on return. Check your standard library’s support; the relevant revision is P2415R2.
Even a view owning its base does not make every iterator independent: some depend on the view itself. borrowed_range describes iterator independence from the range object, not an extension of the underlying storage’s lifetime. When an algorithm cannot safely return an iterator into a temporary range, certain return types use std::ranges::dangling. That is type-level protection, not garbage collection. borrowed_range · dangling.
Continue this discussion in RAII and move semantics. Ranges change composition; ownership remains a design responsibility.
6. Not every range supports every algorithm
Section titled “6. Not every range supports every algorithm”A vector lets you jump directly to element 500. After filtering, finding the 500th accepted element requires searching through earlier candidates. The capability changed, even though the original memory remains contiguous.
| Capability | What it allows |
|---|---|
input_range |
Single-pass reading; restarting is not promised |
forward_range |
Multiple passes through elements |
bidirectional_range |
Moving forward and backward |
random_access_range |
Jumping positions in constant time |
contiguous_range |
Random access plus contiguous elements |
sized_range |
Obtaining size with the required complexity contract; a separate property |
These categories express contracts. A filter over a vector does not preserve random access. std::ranges::sort requires that access and sortable elements. Sorting this view directly therefore fails. Range categories · sort requirements.
Experiment 4 — a real latency report
Section titled “Experiment 4 — a real latency report”Put the pieces together: keep successful requests at or above a threshold, copy the selected records, sort from slowest to fastest and display two. Leave the source untouched.
Mission: in the code below, identify which 900 ms route must be excluded. Then lower the threshold from 100 to 70 and adjust the tests for three selected records. Output still shows only two because of the final take(2).
#include <algorithm>
#include <cassert>
#include <iostream>
#include <ranges>
#include <string>
#include <vector>
struct Request {
std::string route;
int latency_ms;
bool ok;
};
std::vector<Request> slowest(const std::vector<Request>& requests, int limit) {
auto selected = requests | std::views::filter([limit](const Request& r) {
return r.ok && r.latency_ms >= limit;
});
static_assert(!std::ranges::random_access_range<decltype(selected)>);
// Experiment: uncomment the next line to inspect the constraint error.
// std::ranges::sort(selected, std::ranges::greater{}, &Request::latency_ms);
std::vector<Request> result;
for (const auto& r : selected) result.push_back(r);
std::ranges::sort(result, std::ranges::greater{}, &Request::latency_ms);
return result;
}
int main() {
const std::vector<Request> requests{
{"/search", 120, true}, {"/login", 900, false},
{"/feed", 75, true}, {"/checkout", 240, true}
};
auto result = slowest(requests, 100);
assert(result.size() == 2);
assert(result[0].route == "/checkout");
assert(result[1].route == "/search");
assert(slowest({}, 100).empty());
assert(slowest(requests, 1000).empty());
for (const auto& r : result | std::views::take(2))
std::cout << r.route << ' ' << r.latency_ms << " ms\n";
}
Download the complete report (.cpp)
Hint: reading the sorting line
std::ranges::greater{} requests descending order. &Request::latency_ms is the projection: it tells the algorithm which field to compare. Sorting moves complete records, not a separate list of numbers.
Check the report and try the compilation experiment
The original output is:
/checkout 240 ms/search 120 ms/login is excluded because ok is false. At threshold 70, the materialized result also contains /feed: change the call to slowest(requests, 70), update the size assertion to 3 and add assert(result[2].route == "/feed");. The first two records stay the same.
If you download the example to compile locally, uncomment the marked line that attempts to sort selected. Compilation should fail: look for random_access in the diagnostic. Comment it out again to continue. You just turned a template diagnostic into a concrete contract.
Tests also cover empty input and no qualifying candidates. For production, define how equal latencies are ordered, validate the data domain and test predicate boundaries. sort does not promise to preserve the original order of ties; use an explicit policy when that matters.
7. C++23: less ceremony when materializing
Section titled “7. C++23: less ceremony when materializing”The examples use C++20. With C++23 and standard-library support, the report’s copying loop can become:
auto result = selected | std::ranges::to<std::vector<Request>>();This creates a container, not just another view. Selecting a language flag is not enough if the library does not implement the facility. Check __cpp_lib_ranges_to_container after including <version> or the relevant header. ranges::to proposal.
C++23 also expands the toolkit with zip for traversing sequences together, enumerate for index/value pairs, chunk for blocks and slide for overlapping windows. They solve different problems; your next code review does not need all of them. See features by C++ version and the proposals for zip, enumerate and chunk/slide.
8. Performance: what to measure before celebrating
Section titled “8. Performance: what to measure before celebrating”In the report, selection is linear in the input count. Copying needs memory proportional to the selected records. Sorting the m selected records takes O(m log m) comparisons. The final take(2) reduces what we display, not the cost of sorting that already happened.
If you only need the largest two values among millions of records, consider partial selection or a structure that retains just the best candidates. A short pipeline does not replace choosing the right algorithm.
Views can avoid intermediate containers; they do not promise to beat an equivalent loop. Compare identical semantics and inputs, optimize both builds and actually consume the result. Measure allocations, repeated calculations and readability for your team. Compiler Explorer helps inspect generated code; its remote executor is not a reliable latency benchmark for your hardware.
Pipes do not automatically parallelize work, either. For that distinction, read parallelism versus concurrency.
Close the loop: can you explain it without looking?
Section titled “Close the loop: can you explain it without looking?”Take the report and implement a variation: the three fastest successful requests, without modifying the input. Use threshold 0, change the comparator and adjust take. Expect /feed, /search, /checkout, in that order. Then test empty input.
If it worked, you combined selection, materialization, projection and sorting in a small problem that resembles actual work. If you got stuck, return to the specific step that caused uncertainty. There is no prize for reaching the end without testing an idea.
Before approving a pipeline, ask three questions: who owns the data, when does the work happen, and which capabilities does the next algorithm require? With those answers, ranges become a tool you can defend in a code review.
Share experiment 2 with someone before revealing the answer. Which pipeline would they choose for “the first two even numbers”? That conversation teaches more than a screenshot of elegant code. If you find another trap, tag me on X with the smallest example that reproduces it.
References for further reading
Section titled “References for further reading”Standard links point to the living draft, which also includes features newer than C++20. This article’s executable examples deliberately stay with C++20; the C++23 section is marked separately.
- C++ ranges library: contracts and adaptors.
- Constrained algorithms: requirements beyond syntax.
- P2415R2 — views and temporary ranges: the evolution of ownership.