C++의 std::map은 키(Key)와 값(Value)의 쌍을 저장하는 연관 컨테이너다.
내부적으로 레드-블랙 트리(Red-Black Tree)를 사용하여 키를 기준으로 데이터를 자동 정렬하며, 탐색, 삽입, 삭제에 O(log N)의 시간 복잡도를 보장한다.
기본 선언 및 삽입
map은 중복된 키를 허용하지 않는다.
동일한 키로 데이터를 삽입하면 기존 값이 갱신되거나 무시된다.
#include <iostream>
#include <map>
#include <string>
int main() {
// string 키와 int 값을 가지는 map 선언
std::map<std::string, int> inventory;
// 1. insert를 이용한 삽입
inventory.insert(std::make_pair("Apple", 500));
// 2. operator[]를 이용한 삽입 및 갱신
inventory["Banana"] = 300;
inventory["Orange"] = 200;
// 기존 값 갱신
inventory["Apple"] = 600;
return 0;
}
데이터 탐색 및 접근
find() 함수를 사용하여 키의 존재 여부를 확인하고 해당 데이터에 접근할 수 있다.
auto it = inventory.find("Banana");
if (it != inventory.end()) {
std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;
} else {
std::cout << "Key not found." << std::endl;
}
// count()를 이용한 존재 여부 확인 (0 또는 1 반환)
if (inventory.count("Orange")) {
std::cout << "Orange exists." << std::endl;
}
전체 순회
반복자(Iterator)를 사용하여 모든 요소를 순회할 수 있다.
데이터는 키를 기준으로 오름차순 정렬된 상태로 출력된다.
// 범위 기반 for 루프 사용 (C++11 이상)
for (const auto& pair : inventory) {
std::cout << pair.first << " : " << pair.second << std::endl;
}
// 반복자를 직접 사용하는 방식
for (std::map<std::string, int>::iterator it = inventory.begin(); it != inventory.end(); ++it) {
std::cout << it->first << " -> " << it->second << std::endl;
}
데이터 삭제
erase() 함수를 사용하여 특정 키나 범위를 삭제할 수 있다.
// 특정 키 삭제
inventory.erase("Apple");
// 전체 삭제
inventory.clear();
if (inventory.empty()) {
std::cout << "Inventory is empty." << std::endl;
}
P.S
std::map은 데이터를 키 기반으로 구조화하고 정렬된 상태로 유지해야 할 때 효율적이다.
탐색 속도가 중요하지만 정렬이 필요 없는 경우라면 O(1)의 평균 속도를 보장하는 std::unordered_map을 고려할 수 있는 것 같다.