Changing values of vector from for statement

  • Thread starter Thread starter Jeff0803
  • Start date Start date
J

Jeff0803

Guest
I made a simple code like the following.

vector<int> vect{ 10, 20, 30, 40 };

for (int x : vect)
x = x + 5;

for (int x : vect)
cout << x << " ";

The output is

10 20 30 40

However, if I use reference(&x) like following, I can get correct result.(15 25 35,45)

for (int &x : vect)
x = x + 5;

Can anybody explain about why I should use reference here?

Continue reading...
 
Back
Top