The short answer is you can't -
std::vector
has severe problems with references, it was designed to hold values.
So what you need is something that looks like a reference to an
int
but is actually a value. Something like...
class int_ref
{
public:
int_ref( int &ref ) : ref_( ref ){}
operator int &( )
{
return ref_;
}
private:
int &ref_;
};
This looks enough like an
int
that if you make a
vector
of them you can change values through them:
auto main()->int
{
int a = 10, b = 20, c = 30;
std::vector<int_ref> nums{ a, b, c };
std::copy( begin( nums ), end( nums ), std::ostream_iterator<int>( std::cout, "\n" ));
for( auto n : nums ) n+= 10;
std::copy( begin( nums ), end( nums ), std::ostream_iterator<int>( std::cout, "\n" ) );
}
Now this may or may not be a good idea...
int_ref
has some subtle behavioural problems that means it's not quite a reference to an
int
but if all you want to do is modify some other objects through a vector of references to that object then knock yourself out. If you have a use case that needs this sort of thing it might be okay but in general classes with conversion/cast operators like this one are a pain in the bum. They violate most programmers expectations as to how the world works and can be a maintenance nightmare if you don't realise what's going on.