C++

C++ 범위 기반 for문 총정리

김구티2 2024. 3. 14. 20:55

1. 범위 기반(Range-based) For문의 개념

말 그대로, 범위에 대한 for loop을 실행한다. 컨테이너의 모든 요소와 같은 값 범위에 걸쳐 작동하는 기존의 for loop과 동등한 읽기용으로 사용된다. 더 간단하고 안전하게 배열 및 벡터를 반복한다고 생각하면 된다.

 

구문:

for ( range_declaration : range_expression ) 
    loop_statement
Parameters :
range_declaration : 
a declaration of a named variable, whose type is the 
type of the element of the sequence represented by 
range_expression, or a reference to that type.
Often uses the auto specifier for automatic type 
deduction.
range_expression : 
any expression that represents a suitable sequence 
or a braced-init-list.
loop_statement : 
any statement, typically a compound statement, which
is the body of the loop.

 

예시:

// Illustration of range-for loop
// using CPP code
#include <iostream>
#include <map>
#include <vector>
#include<string>

// Driver
int main()
{
    // Iterating over whole array
    std::vector<int> v = { 0, 1, 2, 3, 4, 5 };
    for (auto i : v)
        std::cout << i << ' ';

    std::cout << '\n';

    // the initializer may be a braced-init-list
    for (int n : { 0, 1, 2, 3, 4, 5 })
        std::cout << n << ' ';

    std::cout << '\n';

    // Iterating over array
    int a[] = { 0, 1, 2, 3, 4, 5 };
    for (int n : a)
        std::cout << n << ' ';

    std::cout << '\n';

    // Just running a loop for every array
    // element
    for (int n : a)
        std::cout << "In loop" << ' ';

    std::cout << '\n';

    // Printing string characters
    std::string str = "Guti";
    for (char c : str)
        std::cout << c << ' ';

    std::cout << '\n';

    // Printing keys and values of a map
    std::map<intint> MAP(
        { { 1, 1 }, { 2, 2 }, { 3, 3 } });
    for (auto i : MAP)
        std::cout << '{' << i.first << ", " << i.second
                  << "}\n";
}

 

출력:

0 1 2 3 4 5 
0 1 2 3 4 5 
0 1 2 3 4 5 
In loop In loop In loop In loop In loop In loop 
G u t i
{1, 1}
{2, 2}
{3, 3}

2. 범위 기반 for문의 장단점

우선 장점이 없을 수는 없다. 장점이 없다면 굳이 기존 for문 대신 쓸 이유가 없으니 말이다. 범위 기반 for문의 장점은 ① 짧고 편리하다는 것이 있다. 그러면서 ② for문과 속도 차이도 거의 나지 않고, ③ reference와 auto를 사용할 경우 오히려 빨라지기도 하니 분명 우수성이 존재한다.

 

그러나 ① 모든 배열을 0부터 끝까지 전부 탐색해야 하며, ② 반복 배열의 접근 인덱스가 없다는 것이 단점이다. 인덱스가 없기 때문에 더 하나부터 끝까지 다 해야한다는 것을 의미하기도 한다.

 

728x90

'C++' 카테고리의 다른 글

C++ return문 총정리  (0) 2024.03.17
C++ 함수(functions) 총정리  (0) 2024.03.16
C++ for, while, do while 루프(Loop) 총정리  (1) 2024.03.14
C++ 점프문 총정리  (1) 2024.03.14
C++ 스위치 문 총정리  (1) 2024.03.12