범위 기반 for문(range-based for statement)
예시
#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)
배열 요소를 복사하는 것은 비용이 많이 들 수 있다. 이런 점을 아래와 같이 참조(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 loop)는 고정 배열 뿐만 아니라 std::vector, std::list, std::set, std::map과 같은 구조에서도 작동한다.
<참고>
'C++' 카테고리의 다른 글
(C++) Visual Studio #include <bits/stdc++.h> (0) | 2022.10.07 |
---|---|
(C++) 클래스의 상속 (부모 클래스, 자식 클래스) (0) | 2022.09.03 |
(C++) 정적 멤버와 상수 멤버(static, const) (0) | 2022.09.03 |
(C++) 생성자와 소멸자(디폴트 생성자, 복사 생성자) (2) | 2022.08.20 |
(C++) 메모리의 동적 할당 (0) | 2022.08.20 |