在Java语言中已有基于范围的for循环了,C++98中的fo循环与其比较,使用上繁琐。C++11则引入了基于范围的for循环,使程序变得更加简洁。
一、几组示例:
#include <iostream>
#include <cstdlib>
#include <vector>
#include <algorithm>
using namespace std;
int opera1(int &i) { i *= 10;}
int opera2(int &i) { cout << i << '\t';}
int main()
{
// C++98标准for循环
int array1[5] = {1, 2, 3, 4, 5};
int *pa;
for(pa = array1; pa<array1+sizeof(array1)/sizeof(int); ++pa)
*pa *= 10;
for(pa = array1; pa<array1+sizeof(array1)/sizeof(int); ++pa)
cout << *pa << '\t';
cout << endl;
// C++98 STL库循环
int array2[5] = {1, 2, 3, 4, 5};
for_each(array2, array2+sizeof(array2)/sizeof(int), opera1);
for_each(array2, array2+sizeof(array2)/sizeof(int), opera2);
cout << endl;
// C++11标准基于范围的for循环
int array3[5] = {1, 2, 3, 4, 5};
for(int &i: array3)
i *= 10;
for(int i: array3)
cout << i << '\t';
cout << endl;
// C++98标准模板中使用循环
vector<int> iv1 = {1, 2, 3, 4, 5};
for(auto it = iv1.begin(); it<iv1.end(); ++it)
*it *= 10;
for(auto it = iv1.begin(); it<iv1.end(); ++it)
cout << *it << '\t';
cout << endl;
// C++11标准基于范围的for循环
vector<int> iv2 = {1, 2, 3, 4, 5};
for(auto &it: iv2) // 如果auto it,则值不会改变!
it *= 10;
for(auto it: iv2 )
cout << it << '\t';
cout << endl;
return 1;
}
一切都在不言中,C++11的基于范围的for循环给我们带来了福音!
二、注意事项:
2.1、C++11基于范围的for循环由两部分组成,之间用":"分离,前面是范围内迭代的变量,后面是被迭代的范围,如果要修改迭代范围内的数值,前一项就要使用引用或指针。
2.2、被迭代的范围一定要是确定的且满足++、--操作,STL中的容器和基本类型数组均自动满足,自定义类则要对相关操作符进行重载。关于范围确定,可看如下代码:
int array[] = {1, 2, 3, 4 ,5};
for(int i: array)
cout << i << '\t';
cout << endl;
C++11标准编译不会通过!