여기에서 std::map 유형 객체에 대한 루프 기반 범위를 사용하는 방법을 볼 것입니다. C++에는 지도 유형 객체가 있다는 것을 알고 있습니다. 키 값 쌍을 저장할 수 있습니다. 지도는 기본적으로 쌍 개체를 저장합니다. 이 쌍 개체는 하나의 키와 해당 값을 저장하는 데 사용됩니다. 이러한 키와 값은 템플릿을 사용하여 구현되므로 모든 유형의 데이터를 사용할 수 있습니다.
범위 기반 for 루프를 사용하려면 맵의 각 쌍을 반복할 수 있는 for 루프를 정의할 수 있습니다. 더 나은 아이디어를 얻기 위해 코드를 살펴보겠습니다.
예시 코드
#include<iostream>
#include<map>
using namespace std;
main() {
map<char, string> my_map;
my_map.insert(pair<char, string>('A', "Apple"));
my_map.insert(pair<char, string>('B', "Ball"));
my_map.insert(pair<char, string>('C', "Cat"));
my_map.insert(pair<char, string>('D', "Dog"));
my_map.insert(pair<char, string>('E', "Eagle"));
my_map.insert(pair<char, string>('F', "Flag"));
my_map.insert(pair<char, string>('G', "Ghost"));
my_map.insert(pair<char, string>('H', "Hill"));
my_map.insert(pair<char, string>('I', "India"));
my_map.insert(pair<char, string>('J', "Jug"));
for(auto& key_val : my_map) {
cout << "The " << key_val.first << " is pointing to: " << key_val.second << endl;
}
} 출력
The A is pointing to: Apple The B is pointing to: Ball The C is pointing to: Cat The D is pointing to: Dog The E is pointing to: Eagle The F is pointing to: Flag The G is pointing to: Ghost The H is pointing to: Hill The I is pointing to: India The J is pointing to: Jug