How to set initial size for STL reference_wrapper container?

I have vector

some reference type wrapped in reference_wrapper

. Since I have to fill this container out of order, I am 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 won't compile with an error like:

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


Is there a workaround for this work or do I need to use it vector<T*>

for this purpose?


source to share

2 answers

You can provide a prototype, your own "uninitialized" value:

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




You can use std :: vector :: reserve method.

std::vector< std::reference_wrapper<T> > v;
v.push_back( std::ref( t0 ) ); 
v.push_back( std::ref( t1 ) ); // and etc.. where  t0, t1 - some variable type of T.


Coliru example



All Articles