As a revolutionary standard in C++ history, C++20 has proposed lots of features that would change the way how people programming with C++. And the <ranges>
header and pipes concept are one of them.
To be straightforward, let’s look at an example using the pipes in a for
loop:
The result of this code snippet is to checkout the first 5 number whose square are divisible by 4. The std::views:iota(1)
will generate a sequence of number starting from 1 and increasing by 1. The sequence is floating in a pipe and fed into next two gates: std:views:transform
and std::views::filter
, the former transforms the input into it’s square and the letter only allows elements which are valid judged by its parameter.
Note that std::views::iota
gives out the sequence at runtime (a.k.a. lazy evaluation), so std::views::take
should be used to truncate the sequence, avoiding endless loop.
As we can see, this new style of code is more concise and acting more like functional programming.
Another example:
This loop outputs lower case letters appeared after @
symbol ("haungxtcn"
in this case). In pipes, we can define a more complex lambda expression as in other place.
People have been complaining all the time that there is no elegant way in C++ to split a string. With the help of pipes, we can easily do that: