A custom C++20 range view
source link: https://mariusbancila.ro/blog/2020/06/06/a-custom-cpp20-range-view/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
A custom C++20 range view
Some time ago, I wrote a short post about the C++20 ranges library with examples of how it can simplify our code. Let me take a brief example. Give a sequence of numbers, print the last two even numbers, but in reverse order. This can be written as follows:
This will print 144 and 34. Here is a link to a working program.
In this snippet, filter, reverse, and take are range adaptors, also called views. These range adaptors are class templates available in the namespace std::ranges. They are called filter_view, reverse_view, take_view, and so on. There is a total of 16 views, including other useful ones such as take_while_view, drop_view, drop_while, and transform_view. You can find the entire list here.
For simplicity of use, expressions such as views::filter(R, P), views:take(R, N), or views::reverse(R) are available, although their type and value is unspecified. They are expression-equivalent to filter_view(R, P), take_view(R, N), reverse_view(R), etc.
These range adaptors are lazy. They do not process the adapted range until you start iterating on them. They are also composable using the pipe operator, as we have seen in the snippet above. Moreover, we can write our own range adaptors and use them together with the standard ones.
To see how this works, let’s write a simple range adaptor. Below, you can find a custom, minimum implementation of the take adaptor. We will call this custom_take_view. This takes a range and an integer, representing the number of elements to retain from the range.
Having this, we can re-write the snippet as follows:
The only restriction for this view, as well as for the standard take_view, is that you must specify a count that does not exceed the actual size of the range.
And here are some tests to make sure the view works as expected.
Here is a link to a working sample.
The C++20 ranges library is currently only available with GCC, since version 10. If you don’t have the compiler available, you can try it online with Compiler Explorer or Wandbox.
Like this:
CategoriesC++, UncategorizedTagsC++, c++20, ranges
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK