범위 기반 for 문(C++)

statement의 각 요소에 대해 expression를 반복적 및 순차적으로 실행합니다.

구문

for (for-range-declaration:)
statement

설명

범위 기반 for 문을 사용하여 범위를 통해 실행되어야 하는 루프를 생성합니다. 이 루프는 반복할 수 있는 모든 항목으로 정의됩니다(예std::vector: 범위가 a begin()end()에 의해 정의된 다른 C++ 표준 라이브러리 시퀀스). 부분에 선언된 for-range-declaration 이름은 문에 로컬 for 이며 다시 선언하거나 statement에서 선언 expression 할 수 없습니다. auto 문 부분에서는 키워드(keyword) 선호 for-range-declaration 됩니다.

Visual Studio 2017의 새로운 기능: 범위 기반 for 루프는 더 이상 필요 begin() 없으며 end() 동일한 형식의 개체를 반환합니다. 이렇게 하면 Ranges-V3 end() 제안에 정의된 범위에서 사용하는 것과 같은 sentinel 개체를 반환할 수 있습니다. 자세한 내용은 GitHub에서 범위 기반 For 루프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, goto 범위 return기반 for 루프 외부의 레이블이 지정된 문으로 종료됩니다. 범위 기반 for 루프의 문은 continue 현재 반복만 종료합니다.

범위 기반 for에 대한 다음 사실을 염두에 두세요.

  • 배열을 자동으로 인식합니다.

  • .begin().end()가 포함된 컨테이너를 인식합니다.

  • 기타 항목에 대해 begin()end() 인수 종속성 조회를 사용합니다.

참고 항목

auto
반복 문
키워드
while Statement (C++)
do-while Statement (C++)
for Statement (C++)