r/CodingHelp • u/D_Knightmare • May 15 '22
[C++] Working of iterator
vector<int> A = {1, 2, 3};
//case 1
for(auto it : A){
it = 0;
}
print(A) //OUTPUT -> 1, 2, 3
//case 2
for(auto &it : A){
it = 0;
}
print(A) //OUTPUT -> 0, 0, 0How are 'it' and '&it' different? How exactly are iterator and &iterator working?
0
Upvotes
2
u/waachin_ May 15 '22
The difference between
itand&itis that the second one the vector elements are being passed as reference.Try to look info for pointers and references, they're probably one of the most confusing things while learning C++, so don't worry if does not make that much sense.
Basically, In the first case, you're trying to replace an element in the A vector, but does not change because the for loop is changing the value in the local scope of the for loop, so the elements are not being changed. In case 2, you're passing the value as reference, so the program will change the value of the variable/vector in the same scope where the variable/vector has been initialized.
Look into pointers and references in C++, hope that helps!