for循环的两个代码有什么区别?

问题描述

#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 到向量的元素,这意味着如果你分配它会在引用指向的任何地方覆盖引用的某些内容。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...