Create a view by selecting elements of a range by their index

780 views Asked by At

In range-v3, is there a more efficient way (less steps, cleaner, more expressive, more elegant, more performant, ...) to create a view by selecting elements of a range by arbitrary indexes of the range than using views::counted plus views::concat as in

auto v = std::vector<int> {6,7,8,9,10,11};
auto v1 = views::counted(ranges::begin(v) + 1, 1); // [7]
auto v2 = views::counted(ranges::begin(v) + 3, 1); // [9]
auto v3 = views::counted(ranges::begin(v) + 4, 1); // [10]
auto vFinal = views::concat(v1,v2,v3); // [7,9,10]
1

There are 1 answers

2
parktomatomi On BEST ANSWER

You can wrap up the calls to ranges::views::concat by putting the indices in a range, and calling ranges::views::for_each which maps each element to a function returning a range, then concatenates everything.

auto v = std::vector<int>{6,7,8,9,10,11};
auto i = std::vector<int>{1,3,4};
auto vFinal = i
    | ranges::views::for_each([&v](auto i) { return v | ranges::views::slice(i, i+1); });

https://godbolt.org/z/Wocb8W