👉🏻 C++에서 맵을 사용하는 방법에 대한 설명입니다.
This is an explanation of how to use Maps in C++.
👉🏻 키와 값 형태로 데이터를 저장하고 find()함수로 값으 찾을 수 있습니다.
You can store data in key-value format and find values using the find() function.
👉🏻 코드 / Code
#include <iostream>
#include <map>
#include <string>
int main() {
// std::map 선언: 도시 이름 -> 도시 설명
// 키는 std::string, 값도 std::string
// std::map declaration: City Name -> City Description
// Keys are std::strings, values are also std::strings
std::map<std::string, std::string> route_map;
// 데이터 삽입 / Insert data
route_map["Seoul"] = "Capital of South Korea";
route_map["Busan"] = "Famous port city";
route_map["Jeju"] = "Popular island tourist destination";
// 맵 내용을 출력 / Print map contents
for (const auto& pair : route_map) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
// 특정 키 검색 예제 / Specific key search example
std::string city = "Seoul";
auto iter = route_map.find(city);
if (iter != route_map.end()) {
std::cout << city << " 정보/info.: " << iter->second << std::endl;
} else {
std::cout << city << " 정보를 찾을 수 없습니다. / Can not find information" << std::endl;
}
return 0;
}
✔️ 컴파일 / Compiling
g++ main.cpp -o main -std=c++17
✔️실행 / Run
./main
✔️ 결과 / Result
MacBookAir map % ./main
Busan: Famous port city
Jeju: Popular island tourist destination
Seoul: Capital of South Korea
Seoul 정보/info.: Capital of South Korea