본문 바로가기

Programming/CPP11&14

[C++11] Range-Based For Loop

반응형

C++11에서는 기존의 반복문인 for 문에도 변화가 있었습니다.

기존의 for 문은 다음과 같은 구조로 되어 있었습니다.

for ( init-expression ; cond-expression ; loop-expression )
        statement

초기식과 for loop를 빠져나갈 수 있는 조건, 마지막으로 loop 돌 때마다 실행할 식으로 구성되어 있습니다.

실제 사용에서는 다음과 같은 형태로 사용합니다.

for (int i = 0 ; i < 10 ; i++)
{
	// do something...
}

Range-Based For Loop을 보기 전에 Visual C++의 for each를 먼저 보겠습니다.

for each 문법은 새로운 for 문법과 거의 유사한 형태로 다음과 같이 사용합니다.

for each (type identifier in expression)
{
        statements
}

위와 같은 형식으로 사용됩니다.

문제는 for each는 C++ 표준이 아닌 Microsoft Visual C++만의 문법이라는 점입니다.

STL에 std::for_each가 존재하긴 했으나, for loop가 도중에 중단이 안되는 문제가 있습니다.

C#과 Visual Basic 등에는 이미 foreach나 For Each 같은 구문이 존재합니다.

Range-Based For Loop은 위의 구문들과 같이 Collection(vector, 배열 등)을 기반으로 작동합니다.

문법은 다음과 같습니다.

for ( for-range-declaration : expression )
        statement

Range-Based For Loop의 장점은 STL과 완벽하게 결합이 가능하다는 점입니다.

기본적으로 배열을 자동으로 인식하며, STL의 반복자인 begin()과 end()를 인식하기 때문입니다.

그래서 new나 malloc 등으로 동적 할당된 메모리에 대해서는 사용이 불가능 합니다.

또한 begin()과 end()를 갖고 있지 않는 타입에 대해서 다음과 같은 에러를 표시합니다.

1>c:\fakepath\consoleapplication1.cpp(22): error C3312: no callable 'begin' function found for type 'int'
1>c:\fakepath\consoleapplication1.cpp(22): error C3312: no callable 'end' function found for type 'int'

각 반복문들의 사용법은 코드와 실제 실행 화면으로 확인해 보겠습니다.

#include <iostream>
#include <vector> // for vector
#include <algorithm> // for for_each
using namespace std;

void main()
{
	vector<int> temp = {1, 2, 3, 4, 5};
	
	cout << "Original for loop" << endl;
	for (auto it = temp.begin() ; it != temp.end() ; ++it)
		cout << *it << endl;

	cout << endl << "Visual C++/CLI Style for each" << endl;
	for each (auto& i in temp)
		cout << i << endl;

	cout << endl << "STL for_each using lambda" << endl;
	for_each(temp.begin(), temp.end(), [](int i)
	{
		cout << i << endl;
	});

	cout << endl << "Range-Based for loop" << endl;
	for (auto& i : temp)
		cout << i << endl;
}

결과는 다음과 같이 모두 동일하게 출력됩니다.

STL의 for_each 문에 사용된 문법은 C++11에 추가된 lambda입니다.

C++11의 auto 키워드와 Range-Based For Loop을 활용하면 코드를 효율적으로 작성할 수 있습니다.

반응형