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不会发生任何修改。

 

 

 

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐