multimap 允許重複鍵)。std::less 升序)。std::map mapStudent; // 預設構造
std::map map2(mapStudent); // 拷貝構造
std::map map3(mapStudent.begin(), mapStudent.end()); // 範圍構造
// 1. insert + pair
mapStudent.insert(std::pair(1, "student_one"));
// 2. insert + value_type (推薦,語意更清晰)
mapStudent.insert(std::map::value_type(2, "student_two"));
// 3. 陣列語法 operator[] (會覆蓋既有鍵)
mapStudent[3] = "student_three"; // 若鍵 3 存在,值被覆蓋
insert:**鍵存在時不覆蓋**,回傳 pair 指示成功與否。operator[]:**鍵存在時覆蓋**,若不存在則預設構造值再指派(需值型別可預設構造)。auto result = mapStudent.insert({1, "new"});
if (result.second) {
std::cout << "Inserted: " << result.first->second << '\n';
} else {
std::cout << "Key exists: " << result.first->second << '\n';
}
// 1. find (不修改容器,推薦)
auto it = mapStudent.find(1);
if (it != mapStudent.end()) std::cout << it->second;
// 2. operator[] (若鍵不存在會插入預設值,僅適合確定存在或需插入時)
std::string val = mapStudent[1];
// 3. at (C++11,不存在拋出 out_of_range 異常)
std::string val = mapStudent.at(1); // 安全存取
// 4. count (統計鍵出現次數,map 為 0 或 1)
if (mapStudent.count(1)) { ... }
// C++11 範圍 for (推薦)
for (const auto& [key, value] : mapStudent) {
std::cout << key << ": " << value << '\n';
}
// 傳統迭代器
for (auto it = mapStudent.begin(); it != mapStudent.end(); ++it) {
std::cout << it->first << ": " << it->second << '\n';
}
// 反向遍歷
for (auto it = mapStudent.rbegin(); it != mapStudent.rend(); ++it) { ... }
mapStudent.erase(1); // 按鍵刪除,回傳刪除數量
mapStudent.erase(it); // 按迭代器刪除
mapStudent.erase(it1, it2); // 範圍刪除
mapStudent.clear(); // 清空
find/insert/erase),而非通用演算法(std::find 等),前者利用紅黑樹 O(log n),後者為 O(n)。reserve (C++11 無 map::reserve,可用 unordered_map 或分批插入)。std::map 實現降序或自定排序。find/at/count。| 特性 | map | unordered_map |
|---|---|---|
| 底層結構 | 紅黑樹 | 雜湊表 |
| 順序 | 有序 | 無序 |
| 查找/插入/刪除 | O(log n) | 平均 O(1) |
| 最壞情況 | O(log n) | O(n) |
| 適用場景 | 需有序遍歷、範圍查詢 | 純鍵值查找、極大資料量 |
std::map 是 C++ 標準庫中有序關聯容器的首選。掌握 insert/find/erase 三大核心操作、迭代遍歷模式、以及與 unordered_map 的取捨,能高效解決鍵值映射與排序需求。