C++ Reference ยท Algorithms
C++ projections in std::ranges algorithms
Learn C++20 projections: the proj argument of std::ranges algorithms lets you sort, search and compare by a member or computed key without writing comparators.
A projection is a small callable that the std::ranges algorithms apply to each element before they compare it or call your predicate. It answers the question "what part of the element should the algorithm look at?" so that you do not have to repeat the answer inside every comparator.
Instead of writing a lambda that compares two Person objects by age, you write std::ranges::sort(people, {}, &Person::age). The {} means "use the default comparison" (std::ranges::less) and the third argument is the projection. The elements themselves are rearranged as whole objects; only the comparison sees the projected value.
std::ranges::sort(people, {}, &Person::age); // ascending by age std::ranges::sort(people, std::ranges::greater{}, &Person::age); // descending by age auto it = std::ranges::find(people, "Ann", &Person::name); // find by name
Try it
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.
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
template<input_range R, class Proj = std::identity, indirect_strict_weak_order<projected<iterator_t<R>, Proj>> Comp = ranges::less> constexpr borrowed_iterator_t<R> ranges::max_element(R&& r, Comp comp = {}, Proj proj = {}); // A projection is anything std::invoke can call with one element: // &Class::member pointer to a data member // &Class::method pointer to a const member function without arguments // [](const T& x) { ... } lambda or function object // a free function
| Name | Description |
|---|---|
proj |
A callable applied to each element before it reaches the comparison or predicate. The default, std::identity, returns the element itself. |
comp |
Receives projected values: comp(proj(a), proj(b)). Pass {} to get the default. |
value |
For find, count, lower_bound and similar: compared to proj(element), not to the element. |
Returns: whatever the algorithm normally returns. The projection never changes what is stored, only what is compared.
Errors / undefined behavior: none of its own. A projection must be cheap, deterministic and side-effect free, because algorithms may call it many times per element. Projections that return references to the element's data (member pointers, const& returns) avoid copies; a lambda returning a std::string by value copies on every call.
Usage notes
- Where the projection goes. It is always the last of the optional arguments:
(range, comp, proj)for sorting and heaps;(range, value, proj)forfindandcount;(range, pred, proj)forfind_if,any_of,count_if. That is why you write{}to skip the comparator. - Invoke rules. Projections are called with
std::invoke, so member pointers just work:&Person::ageand&Person::name. Avoid taking the address of standard-library member functions (such as&std::string::size); use a lambda for those. - Two ranges, two projections. Algorithms that take two ranges, such as
ranges::equalandranges::mismatch, haveproj1andproj2. - Unstable sorts. Projections do not make
sortstable. For ties usestable_sort, or use a tuple-returning projection such as[](auto& p) { return std::tie(p.age, p.name); }so that the key is fully distinct. Thetieis a tuple of references, so there is no copying. - Costly projections. Sorting by a computed key like the lowercase string above calls the projection about
2 * n log ntimes. For expensive keys, compute them once into a parallel vector, or use the "decorate-sort-undecorate" pattern. - Searching a sorted range. The projection must be consistent with the order: if the vector is sorted by
age, thenlower_bound(v, 30, {}, &Person::age)is correct, but projecting a different member would not be. - Classic algorithms have no projections.
std::sort(v.begin(), v.end(), cmp)only has a comparator. If you cannot use C++20, write the comparator yourself. See Writing comparators. - Projection or lambda? For a single key, a projection is shorter and clearer. For multi-step logic, a full comparator may be easier to read.