在上面的语法格式中Type declaration表示遍历声明在遍历过程中当前被遍历导的元素会被存储到声明的变量declaration中。expression是要遍历的对象它可以是表达式、容器、数组、初始化列表等。如下代码#include iostream #include vector using namespace std; int main(void) { vectorint t{ 1,2,3,4,5,6 }; for (auto value : t){ //第一次遍历 cout value ; } cout endl; for(int value : t){ //第二次遍历 cout value ; } cout endl; for(auto value : t){ //第三次遍历 cout value ; } cout endl; for(auto value : t){ //第四次遍历 cout value ; } cout endl; for(const auto value : t){ //第五次遍历 cout value ; } return 0; }运行结果1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6 2 3 4 5 6 7 2 3 4 5 6 7在上面的例子中第一次遍历是将容器中的元素拷贝到声明的遍历变量value中 因此无法对value的操作是不影响原数据的所以第二次遍历的结果不会有改变。第二次遍历中声明遍历变量用的int因为这里知道遍历的t容器中全是int类型auto推导出的就是int类型。第三次遍历时遍历变量value声明成引用类型不仅没有拷贝的过程使得效率更高而且对value的操作会直接作用到原数据上因此第四次遍历的结果会全部1。在第五次遍历时遍历变量声明称const autovalue被限制成只读权限如果对value进行操作会报错。使用注意1. 关系型容器在使用基于范围的for循环遍历map容器时#include iostream #include string #include map using namespace std; int main(void) { mapint, string m{ {1, lucy},{2, lily},{3, tom} }; // 基于范围的for循环方式 for (auto it : m) { cout id: it.first , name: it.second endl; } // 普通的for循环方式 for (auto it m.begin(); it ! m.end(); it) { cout id: it-first , name: it-second endl; } return 0; }上述代码使用了基于范围的for循环方式和普通的for循环方式两种方式对map进行遍历注意到使用普通for循环遍历关系型容器时auto自动推导出的是一个迭代器类型需要使用迭代器的类型方式取出元素中的键值对迭代器返回的是地址it-first;it-second;使用基于范围的for循环方式遍历关系型容器时auto自动推导出的类型是容器中的value_type,相当于一个std::pair对象提取键值对的方式it.first;it.second;2. 元素只读在对基于范围的for循环语法的介绍中可以得知在for循环内部声明一个变量的引用就可以修改遍历的表达式中的元素的值但是这并不是用于所有的情况对应set容器来说内部元素都是只读的这是由容器的特性决定的因此在for循环中auto会被是为const auto。#include iostream #include set using namespace std; int main(void) { setint st{ 1,2,3,4,5,6 }; for (auto item : st) { cout item endl; // error, 不能给常量赋值 } return 0; }除此之外在遍历关系型容器map时也会出现同样的问题基于范围的for循环中虽然可以得到一个std::pair引用但是我们是不能修改里面的first值的也就是key值。#include iostream #include string #include map using namespace std; int main(void) { mapint, string m{ {1, lucy},{2, lily},{3, tom} }; for (auto item : m) { // item.first 是一个常量 cout id: item.first , name: item.second endl; // error } return 0; }访问次数基于范围for循环遍历的对象可以是一个表达式或者容器/数组等。在我们对一个容器进行遍历过程中对这个容器的访问次数时一次还是多次呢#include iostream #include vector using namespace std; vectorint v{ 1,2,3,4,5,6 }; vectorint getRange() { cout get vector range... endl; return v; } int main(void) { for (auto val : getRange()) { cout val ; } cout endl; return 0; }上面代码通过getRange()函数对容器v进行访问每访问一次就会输出一次get vector range...。输出结果get vector range... 1 2 3 4 5 6