两种用法的区别
- for(auto a:b)中b为一个容器,效果是利用a遍历并获得b容器中的每一个值,但是a无法影响到b容器中的元素。
- for(auto &a:b)中加了引用符号,可以对容器中的内容进行赋值,即可通过对a赋值来做到容器b的内容填充。
测试代码
#include<iostream>
using namespace std;
int main()
{
int i[10],j;
string s("hello world");
for(auto c : s)
c='v';
cout<<"***********************************************"<<endl;
cout<<s<<endl;
for(auto &c : s)
c='u';
cout<<"***********************************************"<<endl;
cout<<s<<endl;
return 0;
}
测试结果:
***********************************************
hello world
***********************************************
uuuuuuuuuuu