Advanced level · Module 1: Templates and Generic Programming · Lesson 4 of 4
Generic Algorithms with Iterators and Ranges
Design algorithms in the standard library's style so they work with any container, and use C++20 ranges.
In this lesson you will
- Write algorithms that take iterator pairs or ranges
- Use std::ranges algorithms and views
Key concepts
iterator categoriesstd::ranges::sortviews::filter / views::transformlazy evaluation
The lesson
Standard algorithms take iterators rather than containers, so one algorithm works with vectors, arrays and lists. Write your own the same way: template <std::input_iterator It> double mean(It first, It last).
C++20 ranges let algorithms take whole containers: std::ranges::sort(readings). Views compose lazily: readings | std::views::filter(isValid) | std::views::transform(toCelsius) creates no new container; values are computed as you iterate.
Views are cheap to create but refer to the original data, so the data must outlive the view. Materialise results into a container when you need to keep them.
Step by step
- Write an iterator-based count_above template.
- Use it on a vector and a std::array.
- Rewrite a filter–transform loop as a ranges pipeline.
- Copy the view's results into a std::vector.
Practice activity
Process a list of temperature readings with a ranges pipeline that drops invalid values, converts units and finds the maximum.
Expected result: The pipeline gives the same result as an equivalent loop and creates no intermediate containers.
Check your understanding
-
Why do standard algorithms take iterators?
Show answer
So the same algorithm works with many container types.
-
Do views copy the data?
Show answer
No; they evaluate lazily over the original data.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.