C++11中添加了范围for的写法,大大简化了对序列的操作。
范围for(range for)语句遍历给定序列中的每个元素并对序列中的每个值执行某种操作,其语法形式是:
for (declaration : expression) statement
其中:
expression部分是一个对象,必须是一个序列,比方说用花括号括起来的初始值列表、数组或者vector或string等类型的对象。这些类型的共同特点是拥有能返回迭代器的begin和end成员(STL类型+数组?)
#include <iostream>
#include <string>
using namespace std;
int main()
{
string line("Hello World!!!");
for (auto c : line)//范围for(一个对象 : 一个序列),每次迭代,该对象都递增1
cout << c << endl;
string s("C++ is greatest programming languge!!!");
for (auto &a : s)//&a为引用会改变值,auto跟据表达式指向元素类型,算出&a类型
a = toupper(a);//变为大写
cout << s << endl;
return 0;
}
上面简单介绍了范围for在string类中的应用。其实范围for在vector和数组中的应用与之差不多,只是要注意,如果要改变序列中的值,则必须将迭代器声明为引用的形式即(auto &a : range)。否则,不能改变相应的值。
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
cout << "Enter 10 grades!" << endl;
int grades = 0;
vector<int> v(11);
while (cin >> grades)
{
if (grades <= 100)
v[grades / 10]++;
}
for (auto c : v)
cout << c << endl;
return 0;
}
下面将讲解范围for在二维数组中的应用
#include <vector>
#include <iostream>
using namespace std;
int main()
{
int ia[3][4] = {
{0, 1, 2, 3},
{4, 5, 6, 7},
{8, 9, 10, 11}
};
unsigned int counter = 0;//计数器
//在使用范围for遍历多重数组时,除了最内层,其他循环的控制变量都应为引用类型
for(auto &row : ia)
for (auto col : row)
{
if (counter == 4)
{
cout << endl;
counter = 0;
}
counter++;
cout << col << " ";
}
for (auto &row : ia)
for (auto &col : row)
col += 10;
cout << endl;
cout << endl;
counter = 0;
for(auto &row: ia)
for (auto col : row)
{
if (counter == 4)
{
cout << endl;
counter = 0;
}
counter++;
cout << col << " ";
}
return 0;
}
写到这里,有人可能就会问了,我只是单纯的遍历,不对元素进行任何操作,那样是不是就不用加上引用了?
很遗憾,答案是不行。
如果这么写
for(auto row : ia )
for( auto col : row )
这是因为在C++中当编译器会自动的将row初始化为指向ia首元素的指针。这样一来,内层的范围for自然不合法了(范围for的对象必须是有迭代器的序列).