/* 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 }

相关文章:

  • 2021-10-30
  • 2021-09-24
  • 2021-07-04
  • 2021-11-20
  • 2022-01-18
猜你喜欢
  • 2022-12-23
  • 2021-10-15
  • 2022-12-23
  • 2021-11-17
  • 2021-07-01
  • 2021-10-22
相关资源
相似解决方案