Best Practices

Learn how to use constrained algorithms for best practices.

Let’s consider practices that will help out when working with the algorithms we’ve been discussing. We will start by highlighting the importance of actually exploiting the standard algorithms.

Using the constrained algorithms

The constrained algorithms under std::ranges introduced with C++20 offer some benefits over the iterator-based algorithms under std. The constrained algorithms do the following:

  • Support projections, which simplifies custom comparisons of elements.
  • Support ranges instead of iterator pairs. There is no need to pass begin() and end() iterators as separate arguments.
  • Are easy to use correctly and provide descriptive error messages during compilation as a result of being constrained by C++ concepts.

It’s our recommendation to start using the constrained algorithms over the iterator-based algorithms.

Sorting only for the data we need to retrieve

The Algorithm library contains three basic sorting algorithms: sort(), partial_ sort(), and nth_element(). In addition, it also contains a few variants of those, including stable_sort(), but we will focus on these three as, in our experience, it is easy to forget that, in many cases, a complete sort can be avoided by using nth_element() or partial_sort() instead.

While sort() sorts the entire range, partial_sort() and nth_element() could be thought of as algorithms for inspecting parts of that sorted range. In many cases, you are only interested in a certain part of the sorted range, for example:

  • If we want to calculate the median of a range, we require the value in the middle of the sorted range.

  • If we want to create a body scanner that the mean 80% can use by height of a population, we require two values in the sorted range: the value located 10% from the tallest person and the value located 10% from the shortest person.

Get hands-on with 1200+ tech skills courses.