【C++利用auto对std::vector进行遍历时auto的类型】


在这里插入图片描述

结论

当使用for (auto& node:nodes)对std::vector nodes进行遍历时,auto定义的node其实是一个对nodes中对应元素的引用。

具体的探究过程请看下文。

利用auto对std::vector进行遍历

在C++11中,新添加了auto关键字,用该关键字可以方便快捷地对std::vector进行遍历,方式见如下例程。

#include <iostream>
#include <vector>

struct node{
    
    
    int id;
    int coor;
};

int main(void){
    
    
    std::vector<node> arr;
    node tmp;
    for (int i = 1; i<10 ; i++){
    
        //随便放几个数到vector中
        tmp.id = i;
        arr.push_back(tmp);
    }
    
    for (auto& n:arr){
    
    
        std::cout<<n.id<<“ ”;
    }
    
    while (1){
    
    }
    return 0;
}

程序输出结果为

1 2 3 4 5 6 7 8 9

利用auto对vector遍历时,auto的类型

在利用auto对vector进行遍历时,其实生成了一个相应元素的引用,具体见如下代码。

#include <iostream>
#include <vector>

struct node{
    
    
    int id;
    int coor;
};

node& test(std::vector<node>& arr){
    
    
    for (auto& n:arr){
    
    
        std::cout<<"address 2 "<<&arr[0]<<std::endl;
        std::cout<<"address 3 "<<&n<<std::endl;
        return n;
    }
}

int main(void){
    
    
    std::vector<node> arr;
    node tmp;
    for (int i = 1; i<10 ; i++){
    
        //随便放几个数到vector中
        tmp.id = i;
        arr.push_back(tmp);
    }

    for (auto& n:arr){
    
    
        std::cout<<n.id<<“ ”;
    }
    
    std::cout<<"address 1 "<<&arr[0]<<std::endl;
    node& abc = test(arr);
    std::cout<<abc.id<<std::endl;
    std::cout<<"address 4 "<<&abc<<std::endl;
    abc.id = 17;
    std::cout<<abc.id<<std::endl;
    std::cout<<arr[0].id<<std::endl;
  
    while (1){
    
    }
    return 0;
}

输出结果如下

1 2 3 4 5 6 7 8 9 address 1 0x55add4d13f30
address 2 0x55add4d13f30
address 3 0x55add4d13f30
1
address 4 0x55add4d13f30
17
17

根据结果可以看出,test函数中的n其实是一个node&类型的引用,并且该引用可以作为返回值,从而可以进行更多操作。

猜你喜欢

转载自blog.csdn.net/weixin_42483745/article/details/126874950