#include
#include
#include
#include
int main()
{
std::vector v = { 1, 2, 3, 4, 5 };
auto oddnumbersview = v | std::views::filter([](int x) { return x % 2 == 1; });
for (auto el : oddnumbersview)
{
std::cout << el << '
';
}
}
Explanation: we have a simple vector with some elements. Then we create a view range adaptor on that vector, which filters the numbers in the range. For this, we use the pipe operator |. Only the numbers for which the predicate is true are included. In our case, this means the even numbers are excluded. Then we iterate over the filtered view and print out the elements.
Important to note, the underlying vector’s elements are unaffected as we are operating on a view, not on a vector.
Let us create an example which creates a view that returns only numbers greater than 2:
#include
#include
#include
#include
int main()
{
std::vector v = { 1, 2, 3, 4, 5 };
auto greaterthan2view = v | std::views::filter([](int x) { return x > 2; });
for (auto el : greaterthan2view)
{
std::cout << el << '
';
}
}
Now, let us combine the two views into one big view by separating them with multiple pipe | operators:
#include
#include
#include
#include
int main()
{
std::vector v = { 1, 2, 3, 4, 5 };
auto oddandgreaterthan2 = v | std::views::filter([](int x) { return x % 2 == 1; })
| std::views::filter([](int x) { return x > 2; });
for (auto el : oddandgreaterthan2)
{
std::cout << el << '
';
}
}
This example creates a view range adaptor containing odd numbers greater than two. We create this view by combining two different range views into one.
Another ranges adaptors are algorithms. The idea is to have the algorithms overload for ranges. To call an algorithm adaptor we use: std::ranges::algorithm_name(parameters). Example using the std::ranges::reverse() algorithm:
#include
#include
#include
#include
int main()
{
std::vector v = { 1, 2, 3, 4, 5 };
std::ranges::reverse(v);
for (auto el : v)
{
std::cout << el << '
';
}
}
Unlike views, the ranges algorithms modify the actual vector content.
40.4.6 Coroutines
A coroutine is a function that can be suspended and be resumed. The ordinary function is a coroutine if it uses any of the following operators in its function body:
a. co_await – suspends the execution of the coroutine until some other computation is performed, that is until the coroutine itself resumes
b. co_yield – suspends a coroutine and return a value to the caller
c. co_return – returns from a coroutine and stops its execution
20.7 std::span
std::string_view定义的是特定的类型(string),std::span是与std:string_view相同概念的全部类型的应用。
Some containers and types store their elements in a sequence, one next to the other. This is the case for arrays and vectors. We can represent such containers