0

I am totally new to reference_wrapper, so I need a very simple example to understand, please.

I declare two vectors:

std::vector<int> vec;
std::vector<std::reference_wrapper<int>> vec_r;

I fill vec with some values, then I want vec_r to store references to each element of vec, and I want to assign values to vec_r in order to modify the values stored in vec. What should I do?

Hybridslinky
  • 131
  • 1
  • 13
  • You could take a look at the example in the manual: http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper – Galik Jul 03 '17 at 14:10

1 Answers1

4

Initialize vec_r with the contents of vec, using the appropriate constructor:

std::vector<std::reference_wrapper<int>> vec_r(begin(vec), end(vec));

It works because reference wrappers are constructible and assignable from the type they wrap.

Be warned however, that modifying vec after the fact can invalidate everything in vec_r. So tread carefully.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458