基于范围的 for 语句 (C++)

为 expression的每个元素重复并按顺序执行 statement。

for ( for-range-declaration : expression )
   statement 

备注

使用基于范围的 for 语句构造必须通过“范围”执行,定义为任何可以通过为的示例,std::vector的循环,或者范围由 begin() 和 end()定义的其他 STL 序列。 在 for-range-declaration 部分中声明的名称在本地。for 语句,不能重新声明在 expression 或 statement。 请注意 自动 关键字在语句中 for-range-declaration 部分首选方法。

此代码演示如何使用排列) 的 for 循环将数组和向量重复:

// range-based-for.cpp
// compile by using: cl /EHsc /nologo /W4
#include <iostream>
#include <vector>
using namespace std;

int main() 
{
    // Basic 10-element integer array.
    int x[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

    // Range-based for loop to iterate through the array.
    for( int y : x ) { // Access by value using a copy declared as a specific type. 
                       // Not preferred.
        cout << y << " ";
    }
    cout << endl;

    // The auto keyword causes type inference to be used. Preferred.

    for( auto y : x ) { // Copy of 'x', almost always undesirable
        cout << y << " ";
    }
    cout << endl;

    for( auto &y : x ) { // Type inference by reference.
        // Observes and/or modifies in-place. Preferred when modify is needed.
        cout << y << " ";
    }
    cout << endl;

    for( const auto &y : x ) { // Type inference by reference.
        // Observes in-place. Preferred when no modify is needed.
        cout << y << " ";
    }
    cout << endl;
    cout << "end of integer array test" << endl;
    cout << endl;

    // Create a vector object that contains 10 elements.
    vector<double> v;
    for (int i = 0; i < 10; ++i) {
        v.push_back(i + 0.14159);
    }

    // Range-based for loop to iterate through the vector, observing in-place.
    for( const auto &j : v ) {
        cout << j << " ";
    }
    cout << endl;
    cout << "end of vector test" << endl;
}

这是输出:

1 2 3 4 5 6 7 8 9 10

1 2 3 4 5 6 7 8 9 10

1 2 3 4 5 6 7 8 9 10

1 2 3 4 5 6 7 8 9 10

end of integer array test


0.14159 1.14159 2.14159 3.14159 4.14159 5.14159 6.14159 7.14159 8.14159 9.14159

end of vector test

当其中一个在 statement 执行时,基于范围的 for 停止循环:中断返回导航 到带标记的语句在基于范围的 for 循环之外。 在基于范围的 for 循环的一个 继续 语句终止只打印当前迭代。

记住有关基于范围的 for的这些情况:

  • 自动识别数组。

  • 识别具有 .begin() 和 .end()的容器。

  • 另一个的使用依赖于参数的查找 begin() 和 end()。

请参见

参考

auto关键字(类型推导)

迭代语句(C++)

C++关键字

while语句(C++)

do-while 语句 (C++)

对语句(C++)