Search code examples
c++stdvectorreference-wrapper

C++ how to use vector of reference_wrapper


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?


Solution

  • 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.