Standard Library Views

Creating a View of Elements at Even Indices

How do I create a view that only includes elements at even indices?

Abstract art representing computer programming

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 the Numbers vector.

This approach efficiently creates a view without needing additional storage, maintaining the non-owning nature of views.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved