在C++03/98中,不同的容器和数组,遍历的方法不尽相同,写法不统一,也不够简洁,而C++11基于范围的for循环以统一,简洁的方式来遍历容器和数组,用起来更方便了。
#include
#include
using namespace std;
int main()
{
vector arr = {1, 2, 3, 4, 5};
for(auto it = arr.begin(); it != arr.end(); it++)
{
cout << *it << endl;
}
return 0;
}
上面借助auto关键字,省略了迭代器的声明。
现在,在C++11中终于有了基于范围的for循环。
#include
#include
using namespace std;
int main()
{
vector arr = {1, 2, 3, 4, 5};
for(auto n : arr)
{
cout << n << endl;
}
return 0;
}
在上面的基于范围的for循环中,n表示arr中的一个元素,auto则是让编译器自动推导出n的类型。在这里,n的类型将被自动推导为vector中的元素类型int。
在n的定义之后,紧跟一个冒号(:),之后直接写上需要遍历的表达式,for循环将自动以表达式返回的容器为范围进行迭代。
#include
#include
#include
这里需要注意两点:
1、for循环中it的类型是std::pair。因此,对于map这种关联性容器而言,需要使用it.first或者it.second来提取键值。
2、aut自动推导出的类型是容器中的value_type,而不是迭代器。
#include
#include
#include
在该例子中使用了auto &定义了set
同样的细节也会出现在map的遍历中。基于范围的for循环中的std::pair引用,是不能够修改first的。
#include
#include
#include
输出结果:
从上面的结果中可以看到,不论基于范围的for循环迭代了多少次,get_vector()只在第一次迭代之前被调用。
因此,对于基于范围的for循环而言,冒号后面的表达式只会被执行一次。
该篇文章内容来源于《深入应用C++11》