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_mapwordCount;
std::unordered_map idToScore;
上面定义了两个 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{}(p.x) ^ (std::hash{}(p.y) }
};
std::unordered_map pointMap;
常见成员函数总结
size():返回元素个数empty():判断是否为空clear():清空所有元素find(key):返回指向键的迭代器,找不到返回 end()count(key):返回 1(存在)或 0(不存在)insert/pair):插入键值对emplace(args):原地构造新元素erase(key):删除指定键基本上就这些。std::unordered_map 使用简单高效,适合大多数需要快速查找的场景。注意它不保证顺序,如果需要有序,请使用 std::map。
以上就是c++++怎么使用std::unordered_map_c++ std::unordered_map使用方法的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1477762.html
微信扫一扫
支付宝扫一扫