별의 공부 블로그 🧑🏻‍💻
728x90
728x170

범위 기반 for 문(Range-based for Statement)

개념

  • 더 간단하고 안전하게 배열 등의 모든 요소를 반복할 수 있다.
  • 범위(Range)를 통해 실행되어야 하는 루프를 생성한다.
  • C++11 부터 사용 가능

 

구문

attr(optional) for ( init-statement(optional)range-declaration : range-expression )
    loop-statement
속성 설명
attr any number of attributes
init-statement either (since C++20)
▶ an expression statement (which may be a null statement ";")
▶ a simple declaration, typically a declaration of a variable with initializer, but it may declare arbitrarily many variables or be a structured binding declaration
▶ an alias declaration (since C++23)

- Note that any init-statement must end with a semicolon ;, which is why it is often described informally as an epxression or declaration followed by a semicolon.
range-declaration - a declaration of a named variable, whose type is the type of the element of the sequence represented by range-expression, or a reference to that type. 
- Often uses the auto specifier for automatic type deduction.
range-expression any expression that represents a suitable sequence (either an array or an object for which begin and end member functions or free functions are defined) or a braced-init-list.
loop-statement any statement, typically a compound statement, which is the body of the loop.

 

  • range-declaration
    • range-expression의 자료형과 비슷한 named variable 또는 참조(reference)
  • range-expression
    • 배열(array)
    • 시작(begin)과 끝(end) 또는 free 멤버 함수가 있는 객체
    • braced-init-list

 

사용 예

// 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

 

참고

 

Range-based for loop (since C++11) - cppreference.com

Executes a for loop over a range. Used as a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in a container. [edit] Syntax attr(optional) for ( init-statement(optional)range-declaration : range-exp

en.cppreference.com

 

 

 

범위 기반 for 문(C++)

자세한 정보: 문 범위 기반(C++)

docs.microsoft.com

 

728x90
그리드형(광고전용)
⚠️AdBlock이 감지되었습니다. 원할한 페이지 표시를 위해 AdBlock을 꺼주세요.⚠️


📖 Contents 📖