Iterating over collections with the ranges library
The C++ standard library provides three important pillars—containers, iterators, and algorithms—that enable us to work with collections. Because these algorithms are for general purposes and are designed to work with iterators, which define a range, they often require writing explicit and sometimes complex code to achieve simple tasks. The C++20 ranges library has been designed to solve this problem by providing components for handling ranges of elements. These components include range adapters (or views) and constrained algorithms that work with a range instead of iterators. In this recipe, we will look at some of these views and algorithms and see how they can simplify coding.
Getting ready
In the following snippets, we will refer to a function called is_prime()
, which takes an integer and returns a Boolean, indicating whether the number is prime or not. A simple implementation is shown here:
bool is_prime...