C++11引入基于范围的for循环,简化容器和数组遍历:for (declaration : range),如遍历数组int arr[] = {1,2,3,4,5}; for (int x : arr) 输出各元素。

在C++11及以后的标准中,引入了基于范围的for循环(range-based for loop),它提供了一种简洁的方式来遍历容器或数组中的每个元素,而无需手动管理迭代器或下标。
基本语法
范围for循环的基本写法如下:
for (declaration : range) { // 循环体 }
- declaration:声明一个变量,用来接收当前遍历到的元素。
- range:要遍历的容器、数组或任何支持begin()和end()的对象。
遍历数组
例如,遍历一个整型数组:
int arr[] = {1, 2, 3, 4, 5}; for (int x : arr) { std::cout << x << " "; }
输出结果为:1 2 3 4 5
立即学习“C++免费学习笔记(深入)”;
使用引用避免拷贝
如果元素类型较大(如string、自定义类对象),建议使用引用,避免不必要的拷贝:
std::vector<std::string> words = {"hello", "world"}; for (const std::string& word : words) { std::cout << word << " "; }
- 使用const std::string&可以只读访问元素,提升性能。
- 如果需要修改原容器中的元素,使用非const引用:
for (std::string& word : words) { word += "!"; // 修改原元素 }
适用的类型
范围for循环适用于:
- 数组(包括C风格数组)
- 标准库容器(vector、list、set、map等)
- 任何定义了begin()和end()成员函数或支持ADL查找的类型
基本上就这些。用起来简单,但注意是否需要引用、是否允许修改,合理选择声明方式即可。


