C++11提供范围for语句,这个语句遍历给定的序列中的每个元素并对序列中的每个元素执行某种操作:
for (declaration : expression)
statement
string str("some string");
for (auto c : str)
{
cout << c << endl;
}
在for循环中使用auto声明变量c,由编译器决定其类型,每次循环,将str中的下一个字符拷贝到c中。
string s("Hello World!!!");
decltype(s.size()) punct_cnt = 0;
for (auto c : s)
{
if (ispunct(c))
++punct_cnt;
}
cout << punct_cnt << " punctuation characters in " << s << endl;
for (auto &c : s)
{
c = toupper(c);
}
cout << s << endl;
c是string s中字符的引用,使用toupper将string中字符改成大写字符。
原文地址:http://blog.csdn.net/yamingwu/article/details/46351845