【发布时间】:2021-02-18 06:34:42
【问题描述】:
#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;
}
上面的两个代码打印相同的值(1、2、3、4、5)。 但是初始化 &x 和 x 之间有什么不同吗? 感谢阅读!
【问题讨论】:
-
第一个是引用,另一个是值。在第一个示例中,您可以更改
a到x的元素。
标签: c++ reference auto range-based-loop