在C++11中间,引入了范围for语句,它的作用就是简化遍历给定序列的操作。
语法形式如下:
for (declaration : expression)
statement
declaration: 定义的变量
expression: 要遍历的对象
statement: 语句
举例:
string s = "string";
//一般打印字符串s的每个字母的方法
for(int i = 0; i < s.size(); i++)
{
cout << s[i] << " ";
}
//范围for语句
for(auto c : s)
{
cout << c << " ";
}
是不是很简洁?
范围for语句更多的用在容器的遍历:
vector<int> v = {1,2,3};
//一般遍历
for(auto i = v.cbegin(); i != v.cend(); i++)
{
cout << *i << " ";
}
//范围for语句
for(auto i : v)
{
cout << i << " "; //注意,没有*哦
}