C++ std::unordered_map
std::unordered_map 概述
std::unordered_map 是 C++ 标准模板库(STL)中的一个关联容器,基于哈希表实现。它存储键值对,允许通过键快速查找值,平均时间复杂度为 O(1)。
主要特性
- 唯一键:每个键在容器中唯一。
- 无序存储:元素不以任何特定顺序存储。
- 哈希函数:通过哈希函数将键映射到桶(buckets)。
- 动态调整:当负载因子(load factor)超过阈值时,自动重新哈希。
基本用法
包含头文件
#include <unordered_map>
声明和初始化
std::unordered_map<std::string, int> umap; // 空 unordered_map
std::unordered_map<std::string, int> umap = {{"apple", 1}, {"banana", 2}}; // 初始化列表
插入元素
umap.insert({"orange", 3}); // 使用 insert
umap["grape"] = 4; // 使用 operator[]
访问元素
int value = umap["apple"]; // 通过键访问,若键不存在会插入默认值
auto it = umap.find("banana"); // 使用 find 避免自动插入
if (it != umap.end()) {value = it->second;
}
删除元素
umap.erase("apple"); // 通过键删除
auto it = umap.find("banana");
if (it != umap.end()) {umap.erase(it); // 通过迭代器删除
}
遍历元素
for (const auto& pair : umap) {std::cout << pair.first << ": " << pair.second << std::endl;
}
常用成员函数
size():返回元素数量。empty():检查是否为空。clear():清空容器。count(key):返回键的出现次数(0 或 1)。bucket_count():返回桶的数量。load_factor():返回当前负载因子。
性能与优化
- 哈希函数:自定义类型需提供哈希函数或特化
std::hash。 - 负载因子:通过
max_load_factor(float)调整阈值,影响重新哈希的频率。 - 预分配:使用
reserve(size_t)预分配桶以减少重新哈希次数。
示例代码
#include <iostream>
#include <unordered_map>
#include <string>int main() {std::unordered_map<std::string, int> umap = {{"apple", 1}, {"banana", 2}};umap["orange"] = 3;for (const auto& pair : umap) {std::cout << pair.first << ": " << pair.second << std::endl;}if (umap.find("apple") != umap.end()) {std::cout << "Found apple!" << std::endl;}return 0;
}
注意事项
- 键的唯一性:重复插入相同键会覆盖原有值。
- 哈希冲突:性能依赖于哈希函数的质量。
- 迭代器失效:重新哈希操作会使所有迭代器失效。
