The Motivation for the Ranges Library

Get introduced to the Ranges library and its features.

Before we get into the Ranges library itself, let’s discuss why it’s been added to C++20 and why we’d want to use it.

The Ranges library

With the introduction of the Ranges library to C++20 came some major improvements to how we benefit from the standard library when implementing algorithms. The following list shows the new features:

  • Concepts that define requirements on iterators and ranges can now be better checked by the compiler and provide more help during development

  • New overloads of all functions in the <algorithm> header are constrained with the concepts just mentioned and accept ranges as arguments rather than iterator pairs

  • Constrained iterators in the iterator header

  • Range views, which make it possible to compose algorithms

This chapter will focus on the last item: the concept of views, which allow us to compose algorithms to avoid unnecessary data copying to owning containers. To fully understand the importance of this, let’s begin by demonstrating the lack of composability within the algorithm library.

Limitations of the Algorithm library

Standard library algorithms are lacking in one fundamental aspect: composability. Let’s examine what that means by looking at the example from the “Algorithms” chapter, where we discussed this briefly. If you remember, we had a class to represent a Student in a particular year and with a particular exam score:

Get hands-on with 1400+ tech skills courses.