C++11 范围 for
作用
遍历给定序列中的每个元素并对序列中的每个值执行某种操作。
语法
for (declaration : expression)
statement
其中:
expression 部分是一个对象,用于表示一个序列;
declaration 部分负责定义一个变量,该变量被用于访问序列中的基础元素;
每次迭代,declaration 部分的变量会被初始化为 expression 部分的下一个元素值。
示例
不改变原值
例1. 使用范围 for 遍历 string
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str("hello");
for (auto a : str)
{
cout << a << endl;
}
return 0;
}
〖注〗编译环境:[CentOS 7] 、 [g++ 4.8.5] 编译时需要添加 -std=c++11
输出结果:
例2. 使用范围 for 遍历 vector
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> vec;
for (int i = 0; i < 5; ++i)
vec.push_back(i);
for (auto a : vec) // range for
{
cout << "range: " << a << endl;
}
vector<int>::iterator it;
for (it = vec.begin(); it != vec.end(); ++it) // iterator
{
cout << "iterator: " << *it << endl;
}
unsigned int size = vec.size();
for (unsigned int i = 0; i < size; ++i) // at
{
cout << "at: " << vec.at(i) << endl;
}
return 0;
}
输出结果
改变原值
上面两个例子是输出对象中的元素,若要使用范围 for 改变对象中元素的值,则必须把循环变量定义成引用类型。
例3. 使用 range for 改变 string 对象中的字符
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str("hello");
for (auto & a : str) // 引用
{
a = toupper(a);
}
cout << str << endl;
return 0;
}
输出结果:
范围 for 的使用就是这样简单 ?