Creating a View of Elements at Even Indices
How do I create a view that only includes elements at even indices?
Creating a view that includes only the elements at even indices can be accomplished using std::views::filter()
along with a lambda function. The lambda function will check if the index of each element is even.
First, let's set up our example:
#include <iostream>
#include <ranges>
#include <vector>
int main() {
std::vector<int> Numbers{1, 2, 3, 4, 5, 6, 7, 8};
auto EvenIndexView = Numbers
| std::views::filter([i = 0](int) mutable {
return i++ % 2 == 0;
});
for (int Num : EvenIndexView) {
std::cout << Num << ", ";
}
}
1, 3, 5, 7,
In this example, we use a mutable lambda with a captured index variable i
that increments with each call. The lambda returns true
only for even indices. The std::views::filter()
function uses this lambda to filter the Numbers
vector.
Explanation
- The mutable lambda allows modification of the captured variable
i
on each call. i++ % 2 == 0
ensures that only elements with even indices are included.- The
EvenIndexView
is created by applying the filter view to theNumbers
vector.
This approach efficiently creates a view without needing additional storage, maintaining the non-owning nature of views.
Standard Library Views
Learn how to create and use views in C++ using examples from std::views