Z
ZHANK
编程在线教程C++ 教程循环与 range-for
控制流程

循环与 range-for

for/while/do-while、C++11 范围 for( : )、break/continue

循环与 range-for

C++ 兼容 C 的三种循环,但最好的循环是 C++11 引入的范围 for——不用写下标,不会越界。

学完本章你将: 掌握 for/while/do-while、范围 for( : )、break/continue。


for / while / do-while

cpp
#include <iostream>

int main() {
    // for(知道次数)
    for (int i = 0; i < 5; i++) {
        std::cout << i << " ";  // 0 1 2 3 4
    }

    // while(不知道次数)
    int n = 0;
    while (n < 5) { std::cout << n++ << " "; }

    // do-while(至少一次)
    int input;
    do {
        std::cin >> input;
    } while (input < 1 || input > 10);

    return 0;
}

范围 for —— C++11 的杀手特性

cpp
#include <iostream>
#include <vector>

int main() {
    std::vector<int> v = {10, 20, 30, 40, 50};

    // 只读遍历
    for (int x : v) {
        std::cout << x << " ";
    }

    // 修改元素(用引用)
    for (int &x : v) {
        x *= 2;  // v 变成 {20, 40, 60, 80, 100}
    }

    // 避免拷贝(大对象用 const 引用)
    for (const auto &s : strings) {
        std::cout << s << "\n";
    }

    return 0;
}

💡 范围 for 是最安全的循环——没有下标就没有越界。能用范围 for 就别用下标循环。