Best practices
Let's consider practices that will help you out when working with the algorithms we've been discussing. I 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()
andend()
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 my recommendation to start using the constrained algorithms over the iterator-based algorithms.
You may have noticed that this book uses iterator-based algorithms in a lot of places...