컴공생의 다이어리

[c++] 범위 기반 for문 (range-based for statement) 본문

Development/C & C++

[c++] 범위 기반 for문 (range-based for statement)

컴공 K 2021. 1. 15. 03:20

for문은 배열을 반복할 때 편리하고 유연한 방법을 제공하지만, 조금 복잡하고 실수로 인해 오류가 발생하기 쉽다.

C++에서는 범위 기반 for문(range-based for statement)이라는 새로운 유형의 루프를 도입하여 더 간단하고 안전하게 배열 등의 모든 요소를 반복하는 방법을 제공한다.

 

 

범위 기반 for문(range-based for statement)

for(element_declaration : array)
	statement;

범위 기반 for문은 위와 같은 문법 형태를 가진다. 루프는 각 array의 요소를 반복해 element_declaration에 선언된 변수에 현재 배열 요소의 값을 할당한다. 최상의 결과를 얻으려면 element_declaration이 배열 요소와 같은 자료형이어야 한다. 그렇지 않으면 형 변환이 발생한다.

 

범위 기반 for문을 사용해서 arr 배열의 모든 요소를 출력하는 예제이다. for루프가 실행되고 변수 number에 arr배열의 첫번째 요소 값인 1이 할당된다. 그 다음 프로그램에서 1을 출력하는 명령문을 실행한다. 그런 다음 for루프가 다시 실행되고 number가 두번째 요소 값인 2로 할당된다. 이런 식으로 for 루프는 반복할 배열에 원소가 남아있지 않을 때까지 이와 같은 과정을 차례로 반복한다.  (cf) 배열에 대한 인덱스가 아닌 배열의 요소값이 number에 할당)

#include<iostream>
using namespace std;
int main(){
	int arr[]={1,2,3,4,5};
	for(int number : arr)
		cout<<number<<" ";
}

실행결과

 

범위 기반 루프와 auto 키워드(range-based for loops and the auto keyword)

element_declaration은 배열 요소와 같은 자료형을 가져야 하므로, auto 키워드를 사용해서 C++이 자료형을 추론하도록 하는 것이 이상적이다.

#include<iostream>
using namespace std;
int main(){
	int arr[]={1,2,3,4,5};
	for(auto number : arr)
		cout<<number<<" ";
}

 

실행결과

 

범위 기반 for 루프와 참조(ranged-based for loops and references)

앞서 본 예제들에서 element_declaration은 값으로 선언된다. 이것은 반복된 각 배열 요소가 arr에 복사된다. 이렇게 배열 요소를 복사하는 것은 비용이 많이 들 수 있다. 이런 점을 아래와 같이 참조(reference)를 통해 개선할 수 있다. number은 현재 반복된 배열 요소에 대한 참조이므로 값이 복사되지 않는다. 이렇게 참조 되어있을 때 for 문에서 number를 수정한다면 arr 배열의 요소가 수정된다.

#include<iostream>
using namespace std;
int main(){
	int arr[]={1,2,3,4,5};
	for(auto &number : arr)
		cout<<number<<" ";
}

실행결과

만일 참조를 사용하지만 읽기전용으로만 사용하려면 아래와 같이 number를 const로 만드는 것이 좋다.

#include<iostream>
using namespace std;
int main(){
	int arr[]={1,2,3,4,5};
	for(const auto &number : arr)
		cout<<number<<" ";
}

실행결과

성능상(비용 등)의 이유로 ranged-based for 루프에서 참조 또는 const 참조를 사용하는 게 좋다.

 

 

범위 기반 for 루프와 배열이 아닌 것(ranged-based for loops and non-arrays)

범위 기반 for 루프(ranged-based for loop)는 고정 배열 뿐만 아니라 std::vector, std::list, std::set, std::map과 같은 구조에서도 작동한다. ranged-based for문이 유연하다는 것을 알 수 있다.

#include <vector> 
#include <iostream>
using namespace std;
int main() {
	vector<int> arr = { 1,2,3,4,5 };
	for (const auto& number : arr)
		cout << number << " ";
	return 0; 
}

실행결과

 

 

범위 기반 for 루프는 배열에 대한 포인터로 변환된 배열이나 동적 배열의 경우에 작동하지 않는다.

(배열의 크기를 알지 못하기 때문)

 

 

boycoding.tistory.com/210

 

C++ 07.18 - 범위 기반 for 문 (range-based for statement)

범위 기반 for 문 (range-based for statement) '06.06 - for 문' 포스트에서 for 문을 사용하여 배열의 각 요소를 반복하는 예제를 봤다. #include int main() { const int numStudents = 5; int..

boycoding.tistory.com

www.yes24.com/Product/Goods/95863013

 

코딩 테스트를 위한 자료 구조와 알고리즘 with C++

67개 문제 풀이로 익히는 C++ 자료 구조와 알고리즘!코딩 테스트 준비 및 최신 C++ 문법으로 알고리즘을 학습하자!C++ 자료 구조부터 그리디 알고리즘, 분할 정복 알고리즘, 그래프 알고리즘, 동적

www.yes24.com

 

728x90
Comments