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

Joo*_*kyo 2 c++ reference auto range-based-loop

#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;
}
Run Code Online (Sandbox Code Playgroud)
#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;
}
Run Code Online (Sandbox Code Playgroud)

上面的两个代码打印相同的值(1、2、3、4、5)。但是初始化 &x 和 x 之间有什么不同吗?谢谢阅读!

bra*_*ing 5

您编写的代码的输出没有区别。但是,如果您尝试更改x循环中when的值,则会有所不同。

#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;
}
Run Code Online (Sandbox Code Playgroud)

与以下非常不同:

#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;
}
Run Code Online (Sandbox Code Playgroud)

在第二种情况下,向量a将在程序结束时全为零。这是因为,auto通过自身拷贝每个元素的循环内的临时值,而auto &需要参考的向量的元素,这意味着如果你分配的东西它覆盖的任何地方引用指向的参考。