Views in the Standard Library

Learn about range views and utility views, including how to generate, transform, sample, and read files with views.

The Ranges library and non-owning view classes

So far in this chapter, we have discussed views from the Ranges library. As described earlier, these view types need to be constructed in constant time and have constant-time copy, move, and assignment operators. However, in C++, we talked about view classes before the Ranges library was added to C++20. These view classes are non-owning types, just like std::ranges::view, but without the complexity guarantees. In this section, we will begin by exploring the views from the Ranges library that are associated with the std::ranges::view concept and then move on to std::string_view and std::span, which are not associated with std::ranges::view.

Range views

There are already many views in the Ranges library, and we think will see even more of them in future versions of C++. This section will provide a quick overview of some of the available views and also put them in different categories based on what they do.

Generating views

Generating views produce values. They can generate a finite or infinite range of values. The most obvious example in this category is std::views::iota, which produces values within a half-open range. The following snippet prints the values -2, -1, 0, and 1:

Get hands-on with 1400+ tech skills courses.