When I do this:
std::vector<int> hello;
Everything works great. However, when I make it a vector of references instead:
std::vector<int &> hello;
I get horrible errors like
error C2528: 'pointer' : pointer to reference is illegal
I want to put a bunch of references to structs into a vector, so that I don't have to meddle with pointers. Why is vector throwing a tantrum about this? Is my only option to use a vector of pointers instead?
As the other comments suggest, you are confined to using pointers. But if it helps, here is one technique to avoid facing directly with pointers.
You can do something like the following:
As other have mentioned, you will probably end up using a vector of pointers instead.
However, you may want to consider using a ptr_vector instead!
yes you can, look for
std::reference_wrapper
, that mimics a reference but is assignable and also can be "reseated"The component type of containers like vectors must be assignable. References are not assignable (you can only initialize them once when they are declared, and you cannot make them reference something else later). Other non-assignable types are also not allowed as components of containers, e.g.
vector<const int>
is not allowed.By their very nature, references can only be set at the time they are created; i.e., the following two lines have very different effects:
Futher, this is illegal:
However, when you create a vector, there is no way to assign values to it's items at creation. You are essentially just making a whole bunch of the last example.
boost::ptr_vector<int>
will work.Edit: was a suggestion to use
std::vector< boost::ref<int> >
, which will not work because you can't default-construct aboost::ref
.