以範圍為基礎的 for 陳述式 (C++)
對於 statement
中的每個項目,重複且循序地執行 expression
。
語法
for (
for-range-declaration:
運算式)
陳述式
備註
使用範圍型 for
語句來建構必須透過 範圍 執行的迴圈,其定義為您可以逐一查看的任何專案,例如 , std::vector
或任何其他 C++ 標準程式庫序列,其範圍是由 begin()
和 end()
所定義。 在 部分宣告的名稱是 語句的 for-range-declaration
本機名稱, for
無法在 或 statement
中 expression
重新宣告。 請注意, auto
關鍵字在 語句的部分中是慣 for-range-declaration
用的。
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
當其中一個 中的其中一個執行時,範圍型 for
迴圈就會終止: break
範圍 return
型迴圈以外的 for
標籤語句、 或 goto
。 statement
continue
範圍型 for
迴圈中的 語句只會終止目前的反復專案。
請記住這些關於範圍型 for
的事實:
自動辨識陣列。
辨識具有
.begin()
和.end()
的容器。使用與引數相依的查閱
begin()
和end()
以取得任何其他項目。
另請參閱
auto
反覆運算陳述式
關鍵字
while
語句 (C++)
do-while
語句 (C++)
for
語句 (C++)
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應