首页 > 编程语言 > 详细

c++11 auto 与auto& 遍历vector区别

时间:2019-10-14 09:07:12      阅读:923      评论:0      收藏:0      [点我收藏+]

c++11 auto 与auto& 遍历区别

今天被这个问题坑了一天,一直以为是算法错了,debug了一天,最后暴力生成数据才发现,测试代码如下:

?  test vim test.cpp
?  test g++ test.cpp -o test
?  test ./test              
original: 6610
auto: 6610
auto&: 1234
?  test cat test.cpp 
#include<bits/stdc++.h>
using namespace std;
struct node{
        int i;
        string w;
};
int main(){
        vector<node>ns;
        ns.clear();
        ns.push_back({1,"6610"});
        cout<<"original: "<<ns[0].w<<endl;
        for(auto it:ns)it.w="1234";
        cout<<"auto: "<<ns[0].w<<endl;
        for(auto &it:ns)it.w="1234";
        cout<<"auto&: "<<ns[0].w<<endl;
}

区别显而易见,可读和可写。

技术分享图片

c++11 auto 与auto& 遍历vector区别

原文:https://www.cnblogs.com/bllovetx/p/11669320.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!