//代码1:
#include<iostream>
#include<string>
using namespace std;
string s = "hello";
for (auto &i : s ) //i是个引用
i = toupper(i); //i改变成大写,会影响s的值
cout<<s<<endl; //s的值是 HELLO
//
//代码2:
#include<iostream>
#include<string>
using namespace std;
string s = "hello";
for (auto i : s ) //i不是引用
i = toupper(i); //改变成大写,不影响s的值
cout<<s<<endl; //s的值是 hello
总结一下:
for(auto a:b)中b为一个容器,效果是利用a遍历并获得b容器中的每一个值,但是a无法影响到b容器中的元素。
for(auto &a:b)中加了引用符号,可以对容器中的内容进行赋值,即可通过对a赋值来做到容器b的内容填充。