Converting a range to a container
The result of applying various range adapters to a range (such as a container) is a complex type that is difficult to type or remember. Typically, we’d use the auto
specifier to indicate the type of the result of chaining adaptors, as we saw in the previous recipes. Ranges are lazy, which means they are evaluated, and they produce results only when we iterate over them. However, we often need to store the result of applying one or more range adaptors in a container, such as a vector or a map. Prior to C++23, this required explicit coding. However, C++23 provides a range conversion function, called std::ranges::to
, which makes this an easy task. It also enables conversion between different containers. In this recipe, we will learn how to use it.
Getting ready
The is_prime()
function used in the following snippets was shown in the recipe Exploring the standard range adaptors and will not be listed again here.