Here are a few ways you can “pick out” every element at an even index from a range, using only the standard library (C++20/23).
1) If you have C++23’s std::views::stride
#include <iostream>
#include <vector>
#include <ranges>
int main()
{
std::vector<int> v = { 0,1,2,3,4,5,6,7,8,9 };
// stride(2) takes element 0,2,4,6,8…
for (int x : v | std::views::stride(2)) {
std::cout << x << ' ';
}
// prints: 0 2 4 6 8
}
2) Using chunk(2) + transform (C++20)
If your implementation doesn’t yet have stride, you can:
- split the range into non‐overlapping subranges of size 2,
- take the first element of each subrange.
#include <iostream>
#include <vector>
#include <ranges>
int main()
{
std::vector<int> v = { 0,1,2,3,4,5,6,7,8,9 };
auto evens = v
| std::views::chunk(2) // -> { {0,1}, {2,3}, {4,5}, … }
| std::views::transform([](auto sub) { // take the first of each chunk
return *sub.begin();
});
for (int x : evens)
std::cout << x << ' ';
// prints: 0 2 4 6 8
}
3) Zip with an index + filter (C++23-ish)
If you have both std::views::zip and std::views::iota (or use [range-v3]), you can enumerate + filter:
#include <iostream>
#include <vector>
#include <ranges>
// for some stdlibs you may need <range/v3/all.hpp> instead
int main()
{
std::vector<int> v = { 0,1,2,3,4,5,6,7,8,9 };
auto indexed = std::views::zip(
std::views::iota(0), // 0,1,2,3…
v // v[0],v[1],v[2],…
);
auto evens = indexed
| std::views::filter([](auto &&pair){
auto&& [i, val] = pair;
return (i % 2) == 0;
})
| std::views::transform([](auto &&pair){
return std::get<1>(pair); // extract the value
});
for (int x : evens)
std::cout << x << ' ';
// prints: 0 2 4 6 8
}
Which should you pick?
- If you can use C++23’s
std::views::stride(2), that’s the simplest.
- Otherwise,
chunk(2) + transform is pure C++20 and has no external deps.
- If you’re already on Range-v3 (or a C++23 stdlib with
zip), the “enumerate & filter” approach is very flexible for odd/even or more complex predicates.
Hope that helps! 🎉