美文网首页
【转】C++ for(auto &a:b)、for(auto a

【转】C++ for(auto &a:b)、for(auto a

作者: Joyconfirmed | 来源:发表于2023-01-02 15:43 被阅读0次

    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;
    
    int 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;
    }
    

    如果仅仅对b进行读取操作,而不修改,两者效果一致,如下:


    image.png

    如果需要对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");
    }
    
    image.png

    如果不加&符号,则b不会发生任何修改。


    image.png

    From https://blog.51cto.com/u_15295315/2999245

    相关文章

      网友评论

          本文标题:【转】C++ for(auto &a:b)、for(auto a

          本文链接:https://www.haomeiwen.com/subject/swzhcdtx.html