C++如何使用范围for循环(range-based for)?(代码示例)

范围for循环是C++11引入的简化遍历语法,适用于支持begin()/end()的类型,语法为for(declaration:expression),推荐使用const auto&避免拷贝,不可在循环中增删元素。

范围for循环是C++11引入的简化遍历容器或数组的语法,写法简洁、不易越界,适用于所有支持 begin()end() 的类型(如 std::vectorstd::array、原生数组、std::string 等)。

基本语法结构

形式为:for (declaration : expression),其中:

  • declaration 是一个变量声明,代表当前遍历的元素(可带 const 或引用修饰)
  • expression 是一个可迭代对象(必须提供 begin()end()

常见用法示例

// 1. 遍历 vector(只读访问)

#include 
#include 
int main() {
    std::vector nums = {1, 2, 3, 4, 5};
    for (const int& x : nums) {
        std::cout << x << " ";
    }
    // 输出:1 2 3 4 5
}

// 2. 遍历并修改元素(需用引用)

立即学习“C++免费学习笔记(深入)”;

for (int& x : nums) {
    x *= 2; // 修改原容器中的值
}
// nums 变为 {2, 4, 6, 8, 10}

// 3. 遍历 C 风格数组

int arr[] = {10, 20, 30};
for (int x : arr) {
    std::cout << x << " "; // 自动推导长度,无需 sizeof
}

// 4. 遍历 string

std::string s = "abc";
for (char c : s) {
    std::cout << c << "-"; // 输出:a-b-c-
}

注意事项与陷阱

  • 若不需要修改元素,优先用 const auto& 避免拷贝(尤其对大对象)
  • 直接写 auto x 会触发拷贝;写 auto& x 才能修改原值
  • 不能在循环中增删容器元素(会导致迭代器失效,行为未定义)
  • 不适用于需要索引或反向遍历的场景(此时仍用传统 for 或 std::ranges::reverse_view

结合 auto 的推荐写法

让编译器自动推导类型,更安全灵活:

std::vector words = {"hello", "world"};
for (const auto& w : words) { // 推导为 const std::string&
    std::cout << w.length() << " ";
}

// 若确定是数值且不关心类型细节,也可简写为: for (auto x : nums) { / x 是 int 拷贝 / }