statement
의 각 요소에 대해 expression
를 반복적 및 순차적으로 실행합니다.
구문
for (
for-range-declaration:
expression)
statement
설명
범위 기반의 for
문을 사용하여 범위에 대해 실행할 루프를 생성합니다. 범위는 std::vector
와 같이 반복할 수 있는 모든 항목 또는 begin()
및 end()
에 의해 범위가 정의된 기타 C++ 표준 라이브러리 시퀀스로 정의됩니다. for-range-declaration
부분에서 정의된 이름은 for
문에 대해 로컬이며 expression
또는 statement
에서 재정의될 수 없습니다. 문의 for-range-declaration
부분에서는 auto
키워드가 기본 설정됩니다.
Visual Studio 2017의 새로운 기능: 범위 기반 for
루프에서는 더 이상 begin()
및 end()
가 동일한 형식의 개체를 반환하지 않아도 됩니다. 이 기능을 사용하면 end()
가 Ranges-V3 제안에 정의된 대로 범위에서 사용되는 sentinel 개체를 반환할 수 있습니다. 자세한 내용은 Generalizing the Range-Based For
Loop(범위 기반 for 루프 일반화) 및 range-v3 library on GitHub(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
의 다음 중 하나(범위 기반 for
루프 외부의 레이블이 지정된 문에 대한 break
, return
또는 goto
)가 실행될 때 종료됩니다. 범위 기반 for
루프의 continue
문은 현재 반복만 종료합니다.
범위 기반 for
의 경우 다음을 명심하세요.
배열을 자동으로 인식합니다.
.begin()
및.end()
가 포함된 컨테이너를 인식합니다.기타 항목에 대해
begin()
및end()
인수 종속성 조회를 사용합니다.
참고 항목
auto
반복 문
키워드
while
Statement (C++)
do-while
Statement (C++)
for
Statement (C++)