分享方式:


以範圍為基礎的 for 陳述式 (C++)

對於 statement 中的每個項目,重複且循序地執行 expression

語法

for ( for-range-declaration : expression )
陳述式

備註

使用範圍型的 for 陳述式來建構必須透過「範圍」執行的迴圈,這個「範圍」被定義為您可以逐一查看的任何內容,例如 std::vector,或其範圍由 begin()end() 定義的任何其他 C++ 標準程式庫序列。 在 for-range-declaration 部分中宣告的名稱是 for 陳述式的區域變數,不可在 expressionstatement 重複宣告。 請注意,建議在陳述式的 for-range-declaration 部分中使用 auto 關鍵字。

Visual Studio 2017 的新功能: 範圍型的 for 迴圈不再需要 begin()end() 傳回相同類型的物件。 這可讓 end() 傳回 sentinel 物件,例如 Ranges-V3 提案中所定義範圍使用的物件。 如需詳細資訊,請參閱一般化範圍型的 For 迴圈以及GitHub 上的 range-v3 程式庫

此程式碼示範如何使用範圍型的 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 const 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 迴圈會終止:breakreturngoto 到範圍型的 for 迴圈外部的標記陳述式。 範圍型的 for 迴圈中的 continue 陳述式僅終止目前的反覆項目。

請謹記有關範圍型的 for 迴圈的這些特性:

  • 自動辨識陣列。

  • 辨識具有 .begin().end() 的容器。

  • 使用與引數相依的查閱 begin()end() 以取得任何其他項目。

另請參閱

auto
反覆運算陳述式
關鍵字
while 陳述式 (C++)
do-while 陳述式 (C++)
for 陳述式 (C++)