C++11 auto类型说明符如for(atuo &x : s)

#include 

这个头文件包含C++以下头文件:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

在C++prime 中》》
如果要更改字符串中的字符值,我们必须将循环变量定义为引用类型(第2.3.1节,第50页)。请记住,引用只是给定对象的另一个名称。当我们使用引用作为我们的控制变量时,该变量依次绑定到序列中的每个元素。使用引用,我们可以更改引用所绑定的字符。

string s("Hello World!!!");
// convert s to uppercase
for (auto &c : s)   // for every char in s (note: c is a reference)
    c = toupper(c); // c is a reference, so the assignment changes the char
in s
cout << s << endl;
此代码的输出是HELLO WORLD !!!

for循环中的每个迭代初始化一个新的引用

for (auto &c : s)   
    c = toupper(c); 

相当于

for (auto it = s.begin(); it != s.end(); ++it)
{
    auto &c = *it;
    c = toupper(c);
}

你可能感兴趣的:(c++)