#include <vector>
#include <iostream>
using namespace std;
int main(void)
{
vector<int> a = {1, 2, 3, 4, 5};
for (auto &x : a)
cout << x << endl;
}
#include <vector>
#include <iostream>
using namespace std;
int main(void)
{
vector<int> a = {1, 2, 3, 4, 5};
for (auto x : a)
cout << x << endl;
}
Two codes above prints same values (1, 2, 3, 4, 5). But is there different thing between initializing &x and x? Thanks for reading!
There is no difference in the output for the code you wrote. However, if you tried to change the value of
x
when in the loop, there would be a difference.is very different to:
In the second, the vector
a
will be all zeros at the end of the program. This is becauseauto
by itself copies each element to a temporary value inside the loop, whereasauto &
takes a reference to an element of the vector, which means that if you assign something to the reference it overwrites wherever the reference is pointing.