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

来源:互联网 发布:淘宝指数在哪 编辑:程序博客网 时间:2024/06/07 10:01
#include <bits/stdc++.h>

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

#include <iostream>#include <cstdio>#include <fstream>#include <algorithm>#include <cmath>#include <deque>#include <vector>#include <queue>#include <string>#include <cstring>#include <map>#include <stack>#include <set>

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

string s("Hello World!!!");// convert s to uppercasefor (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 charin scout << 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);}