问题描述
#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,5};
for (auto x : a)
cout << x << endl;
}
上面的两个代码打印相同的值(1、2、3、4、5)。 但是初始化 &x 和 x 之间有什么不同吗? 感谢阅读!
解决方法
您编写的代码的输出没有区别。但是,如果您在循环中尝试更改 x
的值,就会有所不同。
#include <vector>
#include <iostream>
using namespace std;
int main(void)
{
vector<int> a = {1,2,3,4,5};
for (auto x : a)
x = 0;
for (auto x : a)
cout << x << endl;
}
与以下内容非常不同:
#include <vector>
#include <iostream>
using namespace std;
int main(void)
{
vector<int> a = {1,5};
for (auto & x : a)
x = 0;
for (auto x : a)
cout << x << endl;
}
在第二个中,向量 a
在程序结束时将全部为零。这是因为 auto
本身将每个元素复制到循环内的一个临时值,而 auto &
需要一个 reference 到向量的元素,这意味着如果你分配它会在引用指向的任何地方覆盖引用的某些内容。