3

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?

Stephan Dollberg
  • 32,985
  • 16
  • 81
  • 107
none
  • 11,793
  • 9
  • 51
  • 87
  • Did you look at the documentation for [std::reference_wrapper](http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper)? It does not provide a default constructor. – Captain Obvlious Sep 19 '14 at 16:30

2 Answers2

5

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

T blank;
std::vector<std::reference_wrapper<T>> v(5, ref(blank));
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
0

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

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

Coliru example

Khurshid
  • 2,654
  • 2
  • 21
  • 29
  • `reverse` doesn't actually increase the size of the vector but only the internal storage of it. As I said I need to push the elements out of order so `push_back` is not an option for me. – none Sep 19 '14 at 20:00
  • Leads to the question of what do you expect the values of v[0] - v[4] if you've only populated v[5]? A reference_wrapper has to refer to _something_. – Andre Kostur Sep 19 '14 at 21:15