C++의 범위 기반 for 루프는 C++ 11부터 추가되었습니다. 이는 범위에 대해 for 루프를 실행합니다. 컨테이너의 모든 요소와 같이 다양한 값에 대해 작동하는 기존 for 루프와 더 읽기 쉬운 것으로 사용됩니다.
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.>
C++ 구현:
C++
// Illustration of range-for loop // using CPP code #include #include #include #include using namespace std; // Driver int main() { // Iterating over whole array vector v = {0, 1, 2, 3, 4, 5 }; for (auto i : v) cout<< i << ' '; cout << '
'; // the initializer may be a braced-init-list for (int n : { 0, 1, 2, 3, 4, 5 }) cout << n << ' '; cout << '
'; // Iterating over array int a[] = { 0, 1, 2, 3, 4, 5 }; for (int n : a) cout << n << ' '; cout << '
'; // Just running a loop for every array // element for (int n : a) cout << 'In loop' << ' '; cout << '
'; // Printing string characters string str = 'Geeks'; for (char c : str) cout << c << ' '; cout << '
'; // Printing keys and values of a map map MAP({ { 1, 1 }, { 2, 2 }, { 3, 3 } }); (auto i : MAP) cout용<< '{' << i.first << ', ' << i.second << '}
'; }> 산출
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 e e k s {1, 1} {2, 2} {3, 3}>
C++ 17 이상: 범위 기반 루프는 다음과 같은 맵과 함께 사용할 수도 있습니다.
for (auto& [key, value]: myMap) { cout << key << ' has value ' << value << std::endl; }>여기서 [키, 값]은 쌍의 요소처럼 작동합니다. 첫 번째 또는 두 번째 키워드를 지정하지 않고 직접 액세스할 수 있습니다.