std::map<Key, T>는 키-값(Key-Value) 쌍을 저장하는 정렬 연관 컨테이너입니다.std::multimap)#include <map>std::map<int, std::string> players;
players.emplace(100, "Alice");
players.emplace(200, "Bob");
std::map<int, std::string> players;
players.insert({100, "Alice"}); // pair 삽입
players.emplace(200, "Bob"); // in-place 생성 삽입
players[300] = "Carol"; // 없으면 생성 후 대입
for (const auto& [id, name] : players) {
std::cout << id << " : " << name << '\n';
}
std::map<int, std::string> mp;
auto [it1, ok1] = mp.insert({1, "one"}); // 키 1 없으면 삽입
auto [it2, ok2] = mp.emplace(1, "uno"); // 키 1 이미 있으면 삽입 안 됨
auto [it3, ok3] = mp.try_emplace(2, "two"); // (C++17) 없을 때만 값 생성
mp.insert_or_assign(1, "ONE"); // (C++17) 있으면 덮어쓰기, 없으면 삽입
try_emplaceinsert_or_assignfind / contains / at / operator[]std::map<int, int> score;
score.emplace(10, 100);
if (auto it = score.find(10); it != score.end()) {
std::cout << it->second << '\n';
}
bool has10 = score.contains(10); // C++20
int s = score.at(10); // 키 없으면 std::out_of_range 예외
score[20] += 5; // 키 20 없으면 0으로 생성 후 += 5
핵심 정리:
find : 가장 일반적인 안전 조회 (end() 비교 필요)contains : 존재 여부만 빠르게 확인 (C++20)at : 없으면 예외 -> "반드시 있어야 하는 키"에 적합operator[] : 없으면 삽입 발생 -> 순수 조회에는 부적합operator[] 함정 (반드시 기억)std::map<int, std::string> mp;
std::string name = mp[100]; // 키 100이 없으면 {100, ""} 삽입됨
find/contains/at를 우선 고려하세요.요약
조회만 한다 -> find / contains / at
없으면 만들어도 된다 -> operator[]
| 연산 | 복잡도 |
|---|---|
find, insert, erase(key) | O(log N) |
lower_bound, upper_bound | O(log N) |
| 순회 전체 | O(N) |
이터레이터 안정성:
insert/emplace는 기존 이터레이터/참조를 무효화하지 않습니다.erase는 삭제된 원소의 이터레이터만 무효화됩니다.map을 쓰나?map이 유리한 경우:
lower_bound/upper_bound 같은 순서 기반 연산 사용O(log N))unordered_map이 유리한 경우:
O(1) 평균)std::map ~= C# SortedDictionary<TKey, TValue>std::unordered_map ~= C# Dictionary<TKey, TValue>insert, try_emplace, insert_or_assign의 차이를 설명할 수 있는가?operator[]가 조회 코드에서 버그를 만들 수 있는 이유는?lower_bound)가 필요할 때 왜 map이 적합한가?