範囲ベースの for ステートメント (C++)
statement
内の各要素に対して expression
を繰り返し順番に実行します。
構文
for (
for-range-declaration:
expression)
statement
解説
範囲ベースの for
ステートメントを使用して、範囲 を通じて実行する必要があるループを構築します。これは反復処理できるもの (たとえば、begin()
および end()
によって範囲が定義される std::vector
やその他の C++ 標準ライブラリ シーケンス) として定義されます。 for-range-declaration
の部分で宣言された名前は for
ステートメントに対してローカルであり、expression
または statement
で再宣言することはできません。 auto
キーワードはステートメントの for-range-declaration
の部分で推奨されることに注意してください。
Visual Studio 2017 の新機能: 範囲ベースの for
ループでは、begin()
および end()
が同じ型のオブジェクトを返す必要はなくなりました。 これにより、end()
が、Ranges-V3 範囲で定義されている範囲で使用されるような sentinel オブジェクトを返すことができます。 詳細については、「範囲ベースの 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
ループは、statement
内の break
、return
、または goto
(範囲ベースの for
ループの外側のラベルが付いたステートメントに対する) が実行されると終了します。 範囲ベースの for
ループ内の continue
ステートメントは、現在のイテレーションのみを終了します。
範囲ベースの for
について、以下の点に注意してください。
自動的に配列を認識します。
.begin()
と.end()
を持つコンテナーを認識します。それ以外については
begin()
およびend()
の引数依存の参照を使用します。
関連項目
auto
繰り返しステートメント
キーワード
while
ステートメント (C++)
do-while
ステートメント (C++)
for
ステートメント (C++)
フィードバック
https://aka.ms/ContentUserFeedback」を参照してください。
以下は間もなく提供いたします。2024 年を通じて、コンテンツのフィードバック メカニズムとして GitHub の issue を段階的に廃止し、新しいフィードバック システムに置き換えます。 詳細については、「フィードバックの送信と表示