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

先把结论摆在最前面,当使用for (auto& node:nodes)std::vector<xxx> 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&类型的引用,并且该引用可以作为返回值,从而可以进行更多操作。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值