C++ 如何使用 for-each 循环 (基于范围的 for 循环)_C++ 范围 for 循环遍历容器方法

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-each 循环,它让遍历容器或数组变得更加简洁直观。你不再需要手动使用迭代器或下标来访问元素。

基本语法

range-based for 循环的基本格式如下:

for (declaration : range) {
    // 操作每个元素
}

其中:

  • declaration:声明一个变量,类型应与容器中元素类型兼容,通常用 auto
  • range:要遍历的容器、数组或其他可迭代对象

遍历普通数组

例如,遍历一个 int 数组:

int arr[] = {1, 2, 3, 4, 5};
for (int x : arr) {
    std::cout << x << " ";
}

输出:1 2 3 4 5

如果想避免复制,尤其是处理大对象时,推荐使用引用:

for (const int& x : arr) {
    std::cout << x << " ";
}

遍历标准容器(如 vector、list、set)

STL 容器天然支持范围 for 循环。例如遍历 vector:

std::vector words = {"hello", "world", "cpp"};
for (const auto& word : words) {
    std::cout << word << " ";
}

这里使用 const auto& 可以自动推导类型并避免拷贝字符串。

如果是 map,可以这样遍历键值对:

std::map ages = {{"Alice", 25}, {"Bob", 30}};
for (const auto& pair : ages) {
    std::cout << pair.first << ": " << pair.second << "\n";
}

修改容器中的元素

如果希望在循环中修改原容器的元素,必须使用非 const 引用:

std::vector nums = {1, 2, 3};
for (auto& x : nums) {
    x *= 2;
}
// nums 现在是 {2, 4, 6}

使用值或 const 引用都无法修改原始数据。

注意事项

  • 范围 for 要求容器支持 begin()end() 函数,标准容器都满足
  • 不能用于动态分配的数组(如 new int[10]),但可用于 std::array 或指针加长度的手动管理方式(不推荐)
  • 循环内部不要添加或删除容器元素,否则可能造成未定义行为
  • 适用于任何实现了 begin/end 的自定义类型

基本上就这些。用好范围 for 循环能让代码更清晰安全。