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

在C++中,std::unordered_map 是一种基于哈希表实现的关联容器,用于存储键值对(key-value pairs),提供平均情况下常数时间复杂度的查找、插入和删除操作。相比 std::map(基于红黑树),它在大多数场景下性能更高,但不保证元素有序。
使用 std::unordered_map 需要包含头文件:
#include <unordered_map>
定义方式如下:
立即学习“C++免费学习笔记(深入)”;
std::unordered_map<Key, Value> map_name;
例如:
std::unordered_map<std::string, int> student_scores;
表示以字符串为键、整数为值的哈希映射。
1. 插入元素
student_scores.insert({"Alice", 95});
student_scores["Bob"] = 87;
student_scores.emplace("Charlie", 90);
注意:使用 [] 会自动创建键(若不存在),并初始化值(如int为0)。
2. 查找元素
auto it = student_scores.find("Alice");
if (it != student_scores.end()) { /* 找到 */ }
if (student_scores.count("Bob")) { /* 存在 */ }
3. 访问值
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);
使用范围 for 循环遍历所有键值对:
for (const auto& pair : student_scores) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
也可使用迭代器方式,但范围for更简洁安全。
若想使用自定义类型(如结构体)作为键,需提供哈希函数和相等比较:
示例:
struct Point { int x, y; };
struct HashPoint {
size_t operator()(const Point& p) const {
return std::hash<int>{}(p.x) ^ (std::hash<int>{}(p.y) << 1);
}
};
std::unordered_map<Point, std::string, HashPoint> point_map;
同时可重载 operator== 或传入额外的等价判断仿函数。
基本上就这些。掌握插入、查找、遍历和自定义键的处理,就能高效使用 std::unordered_map 解决实际问题,比如统计频率、缓存映射、去重等场景。注意避免频繁扩容影响性能,必要时可用 reserve() 预分配空间。
以上就是C++如何使用std::unordered_map_C++哈希容器应用与unordered_map使用方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号