3

Original vector:

std::vector<int> a{1, 2, 3, 4, 5, 6};

vector of indices:

std::vector<int> b{1, 3, 4};

Multiply by 10 each element in a that is indexed by the elements in b. Iterative implementation:

for (auto i = 0; i < b.size(); ++i)
    a[b[i]] *= 10;

Resulting a:

1 20 3 40 50 6

I wonder if I can apply a filter | transform composition from range-v3 to accomplish this? Or could this be done with the pre-range standard algorithms?

cocheci
  • 375
  • 3
  • 7
  • 1
    Transform `b` instead? `b | ranges::view::transform([&a](int i)-> int& { return a[i]; });`? – Jarod42 Mar 22 '21 at 14:49
  • That would indeed filter elements from "a" whose indices are in "b". The question is though how we can get the result that is printed out, i.e. an array containing {1, 20, 3, 40, 50, 6}. – cocheci Mar 22 '21 at 20:01
  • Then you can `action::transform` the transformed `b` view. – Jarod42 Mar 23 '21 at 08:25
  • Slightly odd is that `a[i]` does not necessarily check if `i` is admissible. E.g., `ranges::views::ints(0,10)[100]` works. – Bubaya Jun 30 '22 at 15:33

0 Answers0