首页 > 其他 > 详细

用auto和iterator迭代器对元素赋值比较

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

/* auto赋值只是暂时有效,iterator赋值才是真实有效地*/
/* 不只是vector,所有能用迭代器的容器应该都具有这个特点*/
1
#include<iostream> 2 #include<vector> 3 using namespace std; 4 int main() 5 { 6 vector<int> v; 7 for(int i=0;i<5;i++) 8 v.push_back(i); 9 for(auto i:v)/* 用auto遍历时,对元素赋值只是当场有效。即退出循环便无用*/ 10 { 11 i=7; 12 cout<<i<<endl; 13 } 14 cout<<"上面是auto赋值后元素暂时的值\n"; 15 for(auto i:v) 16 { 17 cout<<i<<endl; 18 } 19 cout<<"上面是auto赋值结束后,元素实际的值"; 20 for(vector<int>::iterator it=v.begin();it!=v.end();it++) 21 { 22 *it=6; 23 cout<<*it<<endl; 24 }/*迭代器赋值才是真实有效*/ 25 cout<<"上面是迭代器对元素赋值后元素的值\n"; 26 for(auto i:v) 27 { 28 cout<<i<<endl; 29 } 30 cout<<"下面是迭代器赋值结束后,元素实际的值,可见这种赋值真实有效\n"; 31 }

用auto和iterator迭代器对元素赋值比较

原文:https://www.cnblogs.com/dayq/p/12038295.html

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