C++中范围for语句

如果想对string对象中的每个字符做点什么操作,目前最好的办法是使用C++11新标准提供的一种语句:范围for(range for)语句。

示例代码:

#include<iostream>
#include<string>
using namespace std;

int main()
{
    string str("some string");
    //每行输出str中的一个字符。
    for (auto c : str)
        cout << c << endl;
    return 0;       
}

如果想要改变string对象中字符的值,必须把循环变量定义成引用类型。
示例代码:

#include<iostream>
#include<string>
#include<cctype>
using namespace std;

int main()
{
    string str("some string");
    //转换成大写形式
    for (auto &c : str)
        c = toupper(c);
    cout << str << endl;
    return 0;       
}
原文地址:https://www.cnblogs.com/huahai/p/7271046.html