Skip to content
Tutorials Center
My learning

Topics

C++ Reference ยท Algorithms

C++ constrained algorithms in std::ranges

Guide to the C++20 std::ranges algorithms: pass whole containers, use projections, get richer return types, and learn what differs from the classic versions.

C++20 added a second copy of most of <algorithm> in the namespace std::ranges. They do the same jobs as the classic ones (sort, find, copy, count, ...), but they take a whole range (a container, an array, a view) instead of an iterator pair, they accept projections, they are checked by concepts, and many return a more useful result than before.

These are not ordinary functions. They are niebloids: function objects you cannot overload, and that argument-dependent lookup does not find. In practice you call them like functions, always with the std::ranges:: prefix.

C++
std::ranges::sort(v);                               // instead of std::sort(v.begin(), v.end())
auto it = std::ranges::find(v, 42);                 // whole container
auto n = std::ranges::count_if(v, [](int x) { return x > 0; });

Try it

C++ Classic versus ranges

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

C++ Richer return types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Syntax

C++
namespace std::ranges {
    // range overload
    template<input_range R, class Proj = identity,
             indirect_strict_weak_order<projected<iterator_t<R>, Proj>> Comp = ranges::less>
    constexpr void sort(R&& r, Comp comp = {}, Proj proj = {});   // simplified

    // iterator + sentinel overload
    template<random_access_iterator I, sentinel_for<I> S, class Comp = ranges::less,
             class Proj = identity>
    constexpr I sort(I first, S last, Comp comp = {}, Proj proj = {});
}
Name Description
r Any range: a container, a C array, a std::string_view, a view. If it is a temporary container, algorithms that return an iterator give back std::ranges::dangling instead.
first, last Iterator and sentinel; the sentinel may be a different type (for example a null terminator marker).
comp / pred A comparison or predicate. Defaults are ranges::less and ranges::equal_to, which require the types to be properly comparable.
proj A projection: a callable (lambda, member pointer, function) applied to each element before the comparison or predicate. Default std::identity.

Returns: often richer than the classic version: result structs named in, out, min, max, found, fun (such as copy_result, for_each_result, minmax_result), or a subrange for remove, unique, search and partition. Algorithms that would return an iterator to a destroyed temporary return std::ranges::dangling instead.

Errors / undefined behavior: invalid ranges and non-strict-weak orderings are still your responsibility. Wrong types fail at compile time with a concept error instead of a long template trace.

Usage notes

  • Same name, same meaning. std::ranges::find(v, 3) is std::find(v.begin(), v.end(), 3). Behavior, complexity and undefined-behavior rules match the classic ones, so everything you know carries over.
  • No begin()/end() mistakes. Passing iterators from two different containers is a classic bug; a single range argument rules it out.
  • Projections replace many small lambdas: std::ranges::sort(people, {}, &Person::age). See Projections. The comparator sees projected values, and {} means "use the default comparison".
  • dangling. std::ranges::find(make_vector(), 3) compiles but returns std::ranges::dangling, which cannot be dereferenced, because the temporary vector would be gone. Store the vector in a variable first.
  • No execution policies. The ranges algorithms have no parallel overloads. Use the classic ones with std::execution::par for that.
  • No ADL, no overload. You cannot customize them by writing your own sort in your namespace, and you cannot pass them where an overload set would work without wrapping in a lambda. std::ranges::sort is a function object, so it can be passed directly, unlike std::sort, which is a template.
  • C++23 additions. ranges::contains, contains_subrange, starts_with, ends_with, find_last, fold_left, fold_right and friends exist only in the ranges namespace.
  • Not everything is constrained. <numeric> algorithms such as iota have ranges versions only from C++23 (std::ranges::iota), and accumulate/partial_sum have none; ranges::fold_left covers accumulate.
  • Compile time. Concept checking makes error messages clearer, but heavy range code can compile a little slower.