C++中的基于范围for循环可自动遍历容器元素。语法为for (declaration : range),支持数组、vector等,如int arr[] = {1,2,3,4,5}; for (int x : arr)可依次处理每个元素。

在C++中,"for each"循环通常指的是基于范围的for循环(range-based for loop),这是从C++11标准引入的一种简洁遍历容器或数组的方式。它能自动遍历序列中的每个元素,无需手动管理迭代器或下标。
语法格式
基本语法如下:
for (declaration : range) {
// 循环体
}
-
declaration:声明一个变量,用来接收当前遍历到的元素。可以使用
auto让编译器自动推导类型。 - range:要遍历的对象,比如数组、vector、list等支持迭代的容器。
常见用法示例
1. 遍历数组
int arr[] = {1, 2, 3, 4, 5};
for (int x : arr) {
std::cout << x << " ";
}
// 输出:1 2 3 4 5
2. 使用 auto 自动推导类型
立即学习“C++免费学习笔记(深入)”;
std::vectorvec = {1.1, 2.2, 3.3}; for (const auto& value : vec) { std::cout << value << " "; } // 推荐对复杂类型使用 const auto& 提高效率
3. 修改容器中的元素(使用引用)
std::vectornums = {10, 20, 30}; for (auto& x : nums) { x += 5; // 直接修改原元素 } // nums 变为 {15, 25, 35}
4. 遍历字符串
std::string str = "hello";
for (char c : str) {
std::cout << c << " ";
}
// 输出:h e l o
注意事项
- 如果只是读取元素,推荐使用
const auto&避免不必要的拷贝。 - 需要修改元素时,使用
auto&获取引用。 - 不适用于需要访问索引的场景(如需索引可配合普通for循环或手动计数)。
- 不能用于C风格字符串(char*),但可用于
std::string。











