Nura
Nura

Reputation: 43

c++ vector operator[] reference

vector<int> vec;
vec.reserve(10);
map<int, vector<int> >hash;
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
vec.push_back(4);

hash[-1] = vec;
vector<int> ref = hash[-1];
ref.push_back(5);
cout <<hash[-1].back() <<endl;  // prints 4
hash[-1].push_back(6);
cout <<hash[-1].back() <<endl;  // prints 6

I'm not sure, why in the code above, hash[-1].back() doesn't print 5 (output is 4). [] operator of vector returns a reference and since I'm adding 5 to the reference, shouldn't it affect hash[-1] ? or is a copy being made how does the last push statement works?

Upvotes: 0

Views: 98

Answers (2)

Shoe
Shoe

Reputation: 76250

With:

vector<int> ref = hash[-1];

you are creating a new vector<int> called ref that is initialized with the copy constructor to hash[-1].

What you really want is to use a reference:

vector<int>& ref = hash[-1];

Upvotes: 2

Luchian Grigore
Luchian Grigore

Reputation: 258618

It returns a reference which you then make a copy of with

vector<int> ref = hash[-1];

Did you mean

vector<int>& ref = hash[-1];

Upvotes: 3

Related Questions