std::unordered_map是基于哈希表的键值对容器,提供平均O(1)的查找、插入和删除操作,不保证元素有序。需包含头文件,定义为std::unordered_map,常用操作包括insert、emplace、[]、find、count、at和erase,支持范围for循环遍历,自定义类型作键需提供哈希函数和相等比较,适用于频率统计、缓存等场景,可调用reserve优化性能。

在C++中,std::unordered_map 是一种基于哈希表实现的关联容器,用于存储键值对(key-value pairs),提供平均情况下常数时间复杂度的查找、插入和删除操作。相比 std::map(基于红黑树),它在大多数场景下性能更高,但不保证元素有序。
基本定义与头文件
使用 std::unordered_map 需要包含头文件:
#include
定义方式如下:
立即学习“C++免费学习笔记(深入)”;
std::unordered_map
例如:
std::unordered_map<:string int> student_scores;
表示以字符串为键、整数为值的哈希映射。
常用操作方法
1. 插入元素
- 使用 insert() 方法:
- 使用下标操作符 [] 或 emplace():
student_scores.insert({"Alice", 95});
student_scores["Bob"] = 87;
student_scores.emplace("Charlie", 90);
注意:使用 [] 会自动创建键(若不存在),并初始化值(如int为0)。
2. 查找元素
- 使用 find() 判断是否存在:
- 或使用 count() 检查键是否存在(返回0或1):
auto it = student_scores.find("Alice");
if (it != student_scores.end()) { /* 找到 */ }
if (student_scores.count("Bob")) { /* 存在 */ }
3. 访问值
- 使用下标操作符直接访问:
- 推荐使用 at() 安全访问(越界抛出异常):
int score = student_scores["Alice"]; // 若键不存在,会创建并返回默认值
int score = student_scores.at("Alice");
4. 删除元素
- 通过键删除:
- 通过迭代器删除:
student_scores.erase("Bob");
auto it = student_scores.find("Charlie");
if (it != student_scores.end()) student_scores.erase(it);
遍历 unordered_map
使用范围 for 循环遍历所有键值对:
for (const auto& pair : student_scores) {
std::cout
}
也可使用迭代器方式,但范围for更简洁安全。
自定义类型作为键
若想使用自定义类型(如结构体)作为键,需提供哈希函数和相等比较:
示例:
struct Point { int x, y; };
struct HashPoint {
size_t operator()(const Point& p) const {
return std::hash
}
};
std::unordered_map
同时可重载 operator== 或传入额外的等价判断仿函数。
基本上就这些。掌握插入、查找、遍历和自定义键的处理,就能高效使用 std::unordered_map 解决实际问题,比如统计频率、缓存映射、去重等场景。注意避免频繁扩容影响性能,必要时可用 reserve() 预分配空间。










