프로그래밍 일반 2014. 4. 2. 15:10

C++ 11 Range-based for loop

웹 컴파일러 링크 : http://melpon.org/wandbox/


Range for


range 안에서 STL의 begin(), end() 에서 하는 것처럼 루프를 실행한다.

모든 표준 컨테이너들은 range로 사용될 수 있고 std::string, initializer 리스트, 배열, 그리고 begin()과 end()를 정의할 수 있는 모든 것[각주:1]들이 사용 가능하다.


문법 

attr(optional) for ( range_declaration : range_expression ) loop_statement


위의 구문은 다음과 유사한 코드를 생성한다.

{

auto && __range = range_expression ; 

for (auto __begin = begin_expr,

__end = end_expr; 

__begin != __end; ++__begin) { 

range_declaration = *__begin; 

loop_statement 


샘플 코드

#include <iostream>

#include <vector>

 

int main() 

{

    std::vector<int> v = {0, 1, 2, 3, 4, 5};

 

    for (int &i : v) // access by reference (const allowed)

        std::cout << i << ' ';

 

    std::cout << '\n';

 

    for (auto i : v) // compiler uses type inference to determine the right type

        std::cout << i << ' ';

 

    std::cout << '\n';

 

    for (int i : v) // access by value as well

        std::cout << i << ' ';

 

    std::cout << '\n';

}


output

0 1 2 3 4 5

0 1 2 3 4 5

0 1 2 3 4 5


참고





  1. 예 istream [본문으로]