skip to content

What do C++20 std::ranges algorithms such as std::ranges::sort(readings, {}, &Reading::timestampMs) offer over the classic std::sort?

level: middleimportance: must knowfreq 50%

answer

  1. pass the whole range
  2. a projection picks the key
  3. concepts check the arguments
  4. they return more than void

basics

~20 s

std::ranges algorithms take a whole range instead of an iterator pair, accept a projection that selects the key to compare (a member pointer works), are constrained by concepts so misuse fails early, and return useful iterators, such as the end of the processed range.

solid answer

~40 s

The `std::ranges` versions of the algorithms, added in C++20, take the container itself: `std::ranges::sort(readings)`. Each accepts a **projection** applied to every element before the comparator or predicate sees it, invoked with `std::invoke`, so a pointer to member works: `std::ranges::sort(readings, {}, &Reading::timestampMs)` sorts by timestamp with the default `std::ranges::less`, and `std::ranges::find(readings, 2, &Reading::sensorId)` finds by id without a lambda. They are **constrained** with concepts such as `std::sortable` and `std::random_access_range`, so `std::ranges::sort` on a `std::list` fails at the call with an unsatisfied constraint. They return information the classic forms drop - `ranges::sort` returns the end iterator, `ranges::copy` returns both ends - and they accept a sentinel of a different type than the iterator. When passed a temporary container, those returned iterators become `std::ranges::dangling`.

code

cpp · 20 lines
cpp
#include <algorithm>
#include <iostream>
#include <vector>

struct Reading {
    int sensorId;
    long long timestampMs;
    double celsius;
};

int main() {
    std::vector<Reading> readings{{3, 1'700, 22.1}, {1, 1'200, 98.0}, {2, 1'500, 21.5}};

    std::ranges::sort(readings, {}, &Reading::timestampMs);          // by member, ascending
    auto it = std::ranges::find(readings, 2, &Reading::sensorId);      // compares sensorId == 2
    auto hottest = std::ranges::max(readings, {}, &Reading::celsius);  // returns a copy

    std::cout << readings.front().sensorId << ' ' << it->celsius << ' '
              << hottest.sensorId << '\n';
}

go deeper

for a junior

Recognise std::ranges::sort(v) as the whole-range form and know a projection like &Reading::timestampMs picks the sort key.

for a middle

Explain projections through std::invoke, the {} comparator placeholder, concept-checked arguments and the richer return types.

for a senior

Use projections to remove hand-written comparator lambdas, read constraint failures quickly, and know where ranges algorithms still lack numeric counterparts.

for a principal

Decide whether new code defaults to std::ranges algorithms and how that interacts with the oldest standard library the team still supports.

## Same algorithms, new interface C++20 added a parallel set of algorithms in namespace `std::ranges` - `std::ranges::sort`, `find`, `find_if`, `max`, `count_if`, `copy`, `transform` and most of the rest. They do what the classic algorithms do, with four interface changes. ## 1. A whole range instead of two iterators ```cpp std::ranges::sort(readings); // instead of std::sort(readings.begin(), readings.end()) ``` Passing the range removes the classic bug of mixing iterators from two containers, and it lets the call accept views directly: `std::ranges::count_if(readings | std::views::take(100), isHot)`. The iterator-pair overloads still exist, and the end may be a **sentinel** of a different type than the iterator, which is what lets ranges represent "until a null terminator" or "until a count runs out" without computing an end iterator first. ## 2. Projections Every ranges algorithm that compares or tests elements takes an optional **projection**, a callable applied to each element first. The default is `std::identity`. The projection is called through `std::invoke`, so a pointer to data member is enough: | Goal | Classic | Ranges | |---|---|---| | sort by timestamp | `std::sort(b, e, [](auto& a, auto& b) { return a.timestampMs < b.timestampMs; })` | `std::ranges::sort(readings, {}, &Reading::timestampMs)` | | find by sensor id | `std::find_if(b, e, [](auto& r) { return r.sensorId == 2; })` | `std::ranges::find(readings, 2, &Reading::sensorId)` | | hottest reading | `std::max_element(b, e, [](auto& a, auto& b) { return a.celsius < b.celsius; })` | `std::ranges::max_element(readings, {}, &Reading::celsius)` | The `{}` passes a default-constructed comparator (`std::ranges::less`) so the projection can follow it. A projection keeps the comparator generic and the key selection separate, which also removes the classic mistake of comparing different members on the two sides of a hand-written lambda. ## 3. Concept constraints The ranges algorithms are constrained with C++20 concepts: `std::ranges::sort` requires a `std::ranges::random_access_range` whose iterator is `std::sortable` with the given comparator and projection. Calling it on a `std::list` fails at the call site with a message about an unsatisfied constraint, rather than deep inside the algorithm's implementation. The concepts check syntax only: a comparator that compiles but is not a strict weak ordering still gives undefined behaviour. ## 4. Richer return values - `std::ranges::sort` returns an iterator equal to the end of the range, which matters when the end was a sentinel. - `std::ranges::copy` and `std::ranges::transform` return result structs such as `in_out_result` with both the input position reached and the output position written. - `std::ranges::find` returns an iterator, as before, but called on a temporary container it returns `std::ranges::dangling` so the result cannot be used by mistake. - `std::ranges::max` and `std::ranges::min` on a range return the **value**, a copy; use `max_element` for an iterator. ## Other differences worth knowing - The ranges algorithms are **algorithm function objects** (often nicknamed niebloids): objects that are not found by argument-dependent lookup and cannot be called with explicit template arguments, so `using namespace std::ranges;` does not make `sort(v)` pick a different overload by accident. - The default comparator `std::ranges::less` requires `std::totally_ordered`, so a type that defines only `operator<` cannot be sorted with `std::ranges::sort(v)`: Apple clang 21 reports that `sortable<...>` evaluated to false. Define the full set of comparisons - C++20's defaulted `operator<=>` provides them - or pass a projection or comparator. - `std::accumulate` and `std::reduce` have no `std::ranges` counterparts; C++23 added `std::ranges::fold_left` and its relatives, and `std::ranges::iota`, instead. ## Projections with views Projections combine naturally with views, because a ranges algorithm accepts any range. To find the first reading over a threshold among the most recent hundred: ```cpp auto recent = readings | std::views::reverse | std::views::take(100); auto it = std::ranges::find_if(recent, [](double c) { return c > 90.0; }, &Reading::celsius); ``` The projection extracts `celsius`, the predicate stays a plain function of a `double`, and `it` is an iterator into the view. Two cautions apply when mixing the two styles: - an iterator into a view is only meaningful while that view and its source are alive; - converting it back to a position in `readings` needs `.base()` on the reverse iterator, which is easy to get wrong - often it is clearer to search `readings` directly with a projection. ## In the telemetry pipeline Sorting a batch of readings by timestamp, finding the first reading from a sensor and taking the hottest are one call each, with no lambdas: `std::ranges::sort(batch, {}, &Reading::timestampMs);`, `std::ranges::find(batch, id, &Reading::sensorId);`, `std::ranges::max(batch, {}, &Reading::celsius);`.

  • What does the {} argument in std::ranges::sort(readings, {}, &Reading::timestampMs) stand for?
    It value-initialises the comparator parameter, whose default type is `std::ranges::less`, so the call can pass the projection as the next argument. The algorithm then compares `std::invoke(proj, a) < std::invoke(proj, b)`, here `a.timestampMs < b.timestampMs`. Passing `std::ranges::greater{}` instead sorts newest first with the same projection.
  • Why does std::ranges::sort on a std::list fail differently from std::sort on a std::list?
    `std::ranges::sort` is constrained: it requires a `random_access_range`, so overload resolution rejects the call and the compiler reports the unsatisfied constraint at the call site. Classic `std::sort` is an unconstrained template, so it is instantiated and fails inside the library on an operation like `last - first` that list iterators lack, with a longer and less direct error.

  • Saying the ranges algorithms are the same functions with a container overload
  • Writing a lambda for every key instead of a member-pointer projection
  • Believing concepts verify that a comparator is a strict weak ordering
  • Expecting std::ranges::max to return an iterator
  • Assuming std::ranges has an accumulate in C++20

Assumes C++23; std::ranges algorithms, projections and concepts are C++20, and std::ranges::fold_left is C++23.