std::unordered_map是基于哈希表的关联容器,提供O(1)平均查找、插入和删除效率。需包含头文件,支持通过下标、insert或emplace插入元素;find和count用于查找;at方法安全访问元素,避免自动插入;erase删除元素;可使用范围for或迭代器遍历。自定义类型作键时需提供哈希函数与等于比较。常见成员函数包括size、empty、clear等。无序性使其区别于有序的std::map。

在C++中,std::unordered_map 是一个基于哈希表实现的关联容器,用于存储键值对(key-value pairs),并提供平均情况下 O(1) 的查找、插入和删除效率。它定义在
包含头文件并声明 unordered_map
使用前需要包含对应的头文件,并根据键和值的类型进行声明:
#include#include iostream>
std::unordered_map<:string int>wordCount;
std::unordered_map
上面定义了两个 map:一个以字符串为键、整数为值;另一个以整数为键、双精度浮点数为值。
常用操作方法
1. 插入元素
立即学习“C++免费学习笔记(深入)”;
有多种方式可以插入数据:
- 使用下标操作符:wordCount["hello"] = 1;(如果键不存在会自动创建)
- 使用 insert 方法:wordCount.insert({"world", 2});
- 使用 emplace 原地构造:wordCount.emplace("cpp", 3);
2. 查找元素
通过 find 或 count 判断是否存在指定键:
auto it = wordCount.find("hello");if (it != wordCount.end()) {
std::cout second }
或者用 count(返回 0 或 1):
if (wordCount.count("hello")) {std::cout }
3. 访问元素
使用下标访问时,若键不存在,会自动插入一个默认初始化的值:
int value = wordCount["not_exist"]; // 插入 key="not_exist", value=0更安全的方式是先检查是否存在,或使用 at() 方法(越界会抛出 std::out_of_range 异常):
try {int val = wordCount.at("hello");
} catch (const std::out_of_range& e) {
std::cout }
4. 删除元素
使用 erase 删除指定键或迭代器指向的元素:
wordCount.erase("hello"); // 删除键为 "hello" 的元素wordCount.erase(it); // 删除迭代器位置的元素
5. 遍历 unordered_map
使用范围 for 循环遍历所有键值对:
for (const auto& pair : wordCount) {std::cout }
也可以使用迭代器:
for (auto it = wordCount.begin(); it != wordCount.end(); ++it) {std::cout first " second }
自定义类型作为键
如果想用自定义类型(如结构体)作为键,需要提供哈希函数和等于比较:
struct Point {int x, y;
bool operator==(const Point& other) const {
return x == other.x &&& y == other.y;
}
};
struct HashPoint {
size_t operator()(const Point& p) const {
return std::hash
};
std::unordered_map
常见成员函数总结
- size():返回元素个数
- empty():判断是否为空
- clear():清空所有元素
- find(key):返回指向键的迭代器,找不到返回 end()
- count(key):返回 1(存在)或 0(不存在)
- insert/pair):插入键值对
- emplace(args):原地构造新元素
- erase(key):删除指定键











