개인공부/C++
범위 기반 for 문(range-based for statement)
Itsumo
2023. 3. 14. 13:34
범위 기반 for 문의 문법
1
2
|
for (element_declartion : array)
statement;
|
cs |
루프는 각 array 의 요소를 반복하여 element_declaration에 선언된 변수에 현재 배열 요소의 값을 할당한다. 최상의 결과를 얻으려면 element_declararion 이 배열 요소와 같은 자료형이어야 한다. 그렇지 않으면 형 변환이 발생한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> vec;
for (int i = 0; i < 10; ++i)
vec.push_back(i);
for (const auto& num : vec)
{
cout << num << '\n';
}
return 0;
}
|
cs |
num 값에는 vec[i] 번째 값을 반환해준다