Search code examples
c++c++11stlreference-wrapper

How to set an initial size for an STL container of reference_wrapper?


I have a vector of some reference type wrapped in reference_wrapper. Since I need to fill this container out of order I'm trying to set an initial size for the container:

vector<std::reference_wrapper<T>> v(5);

v[3] = ..
v[2] = ..
v[4] = ..
v[5] = ..
v[1] = ..

This fails to compile with an error like:

error: no matching function for call to ‘std::reference_wrapper<int>::reference_wrapper()’

Is there a workaround to make this work or do I have to use a vector<T*> for this purpose?


Solution

  • You could provide a prototype, sort of your own "uninitialised" value:

    T blank;
    std::vector<std::reference_wrapper<T>> v(5, ref(blank));