C++ - Vector "false incrementing"

What does this code do? In particular, why operation item += 2, iterated over all elements of the vector, doesn't change it? #include <iostream> #include <vector> using namespace std; int main() { vector<int> ar = {1,2,3}; for(auto item : ar) item += 2; for(auto item : ar) cout << item; return 0; }

10/18/2019 11:32:13 AM

Paolo De Nictolis

2 Answers

New Answer


if you use 'auto &' instead of only 'auto' it'll increment actual element of vector. auto was introduced in c++11. the appropriate type is deduced based on initializer. if you do something like auto a= 1.2f; //it'll deduce appropriate type i.e float In your code this line for(auto item : ar) is same as for(int item : ar) Because all elements of vector are int. If you explicitly write 'auto &' or 'int &' you can increment values of vector through reference. Endnote: Don't take it seriously I have no knowledge of vectors(know about auto though) 😁. Hope someone will come with better answer 😋👌 edit : Dennis got it 😄


for( : ) is a range based for loop. https://en.cppreference.com/w/cpp/language/range-for auto makes the compiler figure out what the type should be. In this case since 'ar' contains ints, 'auto item' is deduced to be an int. Just as you would expect with normal copying of variables, this too, creates a copy of each value in ar as it iterates through it. It then increments the copy by 2 and discards it. Same thing as if you did this: int a = 1; int b = a; b += 2; If you want the actual value inside the vector to be changed you have to tell it you want a reference instead of a copy, simply add & after auto so you have: `for( auto& item : ar )` Same thing as if you did this: int a = 1; int& b = a; b += 2;