b为数组或容器,是被遍历的对象
for(auto &a:b),循环体中修改a,b中对应内容也会修改
for(auto a:b),循环体中修改a,b中内容不受影响
for(const auto &a:b),a不可修改,用于只读取b中内容
#include <iostream>
using namespace std;
void main()
{
int arr[5] = {1,2,3,4,5};
for (auto &a : arr)
{
cout << a;
}
cout << endl;
for (auto a : arr)
{
cout << a;
}
cout << endl;
system("pause");
}
如果仅仅对b进行读取操作,而不修改,两者效果一致,如下:

如果需要对b进行修改,则需要用for(auto &a:b),如下:
#include <iostream>
using namespace std;
void main()
{
int arr[5] = {1,2,3,4,5};
for (auto &a : arr)
{
a++;
}
for (auto a : arr)
{
cout << a;
}
cout << endl;
system("pause");
}

如果不加&符号,则b不会发生任何修改。
本文深入探讨了C++中引用与迭代器在for循环中的应用,对比了使用引用和非引用方式遍历数组或容器的区别。通过具体示例说明了如何利用引用在循环中修改容器元素,以及非引用方式的读取特性。
3041





