unordered_map是基于哈希表的C++关联容器,提供O(1)平均时间复杂度的查找、插入和删除操作,不保证元素有序;需包含头文件<unordered_map>并使用std命名空间;声明方式为unordered_map<Key_Type, Value_Type> name,可直接初始化键值对;插入可用insert、下标或emplace,推荐emplace更高效;查找推荐使用find配合迭代器判断是否存在,或count返回0/1;访问值时下标操作符会隐式插入默认值,建议先检查存在性或用at()避免错误;删除用erase传键或迭代器;遍历支持范围for循环或迭代器;自定义类型作键时需提供哈希函数;注意避免下标误插、频繁重哈希,可通过reserve预分配空间提升性能。

unordered_map 是 C++ 标准库中提供的关联式容器,基于哈希表实现,用于存储键值对(key-value pairs),能够以接近常数时间复杂度 O(1) 完成查找、插入和删除操作。相比 map(基于红黑树),unordered_map 查询更快,但不保证元素有序。
包含头文件与命名空间
使用 unordered_map 需要包含对应的头文件,并引入 std 命名空间:
#include <unordered_map>#include <iostream>
using namespace std;
声明与初始化
基本语法如下:
unordered_map<Key_Type, Value_Type> map_name;例如:
立即学习“C++免费学习笔记(深入)”;
unordered_map<string, int> student_scores;unordered_map<int, string> id_to_name;
也可以在定义时初始化:
unordered_map<string, int> scores = {&{"Alice", 95},
&{"Bob", 87},
&{"Charlie", 90}
};
常用操作方法
1. 插入元素
- 使用 insert() 方法: student_scores.insert({"David", 88});
- 使用下标操作符 [] 或 emplace(): student_scores["Eve"] = 92; // 若键不存在则创建,存在则覆盖
student_scores.emplace("Frank", 76); // 更高效,原地构造
2. 查找元素
- 使用 find() 判断是否存在: auto it = student_scores.find("Alice");
- 使用 count() 检查键是否存在(返回 0 或 1): if (student_scores.count("Bob")) {
if (it != student_scores.end()) {
&cout << "Score: " << it->second << endl;
}
&cout << "Bob exists." << endl;
}
3. 访问值
- 通过下标访问(若键不存在会自动创建,默认初始化值): cout << student_scores["Alice"] << endl;
- 推荐先检查是否存在,避免意外插入: if (student_scores.find("Alice") != student_scores.end()) {
&cout << student_scores.at("Alice") << endl; // 使用 at() 更安全,越界会抛异常
}
4. 删除元素
- 使用 erase() 删除指定键: student_scores.erase("Bob");
- 也可传入迭代器删除: auto it = student_scores.find("Charlie");
if (it != student_scores.end()) {
&student_scores.erase(it);
}
5. 遍历容器
使用范围 for 循环遍历所有键值对:
for (const auto& pair : student_scores) {&cout << pair.first << ": " << pair.second << endl;
}
或使用迭代器:
for (auto it = student_scores.begin(); it != student_scores.end(); ++it) {&cout << it->first << " - " << it->second << endl;
}
自定义哈希函数(可选进阶)
如果键类型不是内置类型(如自定义结构体),需提供哈希函数:
struct Point {&int x, y;
&bool operator== (const Point& p) const {
&return x == p.x && y == p.y;
&}
};
struct HashPoint {
&size_t operator()(const Point& p) const {
&return hash<int>{}(p.x) ^ (hash<int>{}(p.y) << 1);
&}
};
unordered_map<Point, string, HashPoint> point_map;
基本上就这些。unordered_map 使用简单、效率高,适合需要快速查找的场景。注意避免频繁重哈希(可通过 reserve() 预分配空间),并合理选择键类型。不复杂但容易忽略细节,比如下标访问可能造成隐式插入。用好 find 和 count 能更安全地操作数据。








