首页 > 后端开发 > C++ > 正文

c++怎么使用std::unordered_map_c++ std::unordered_map使用方法

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

c++怎么使用std::unordered_map_c++ std::unordered_map使用方法

在C++中,std::unordered_map 是一个基于哈希表实现的关联容器,用于存储键值对(key-value pairs),并提供平均情况下 O(1) 的查找、插入和删除效率。它定义在 <unordered_map> 头文件中。

包含头文件并声明 unordered_map

使用前需要包含对应的头文件,并根据键和值的类型进行声明:

#include <unordered_map>
#include <iostream>

std::unordered_map<std::string, int> wordCount;
std::unordered_map<int, double> 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 << "Found: " << it->second << std::endl;
}

或者用 count(返回 0 或 1):

if (wordCount.count("hello")) {
    std::cout << "Key exists" << std::endl;
}

3. 访问元素

LibLibAI
LibLibAI

国内领先的AI创意平台,以海量模型、低门槛操作与“创作-分享-商业化”生态,让小白与专业创作者都能高效实现图文乃至视频创意表达。

LibLibAI 159
查看详情 LibLibAI

使用下标访问时,若键不存在,会自动插入一个默认初始化的值:

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 << "Key not found!" << std::endl;
}

4. 删除元素

使用 erase 删除指定键或迭代器指向的元素:

wordCount.erase("hello"); // 删除键为 "hello" 的元素
wordCount.erase(it); // 删除迭代器位置的元素

5. 遍历 unordered_map

使用范围 for 循环遍历所有键值对:

for (const auto& pair : wordCount) {
    std::cout << pair.first << ": " << pair.second << std::endl;
}

也可以使用迭代器:

for (auto it = wordCount.begin(); it != wordCount.end(); ++it) {
    std::cout << it->first << " -> " << it->second << std::endl;
}

自定义类型作为键

如果想用自定义类型(如结构体)作为键,需要提供哈希函数和等于比较:

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<int>{}(p.x) ^ (std::hash<int>{}(p.y) << 1);
    }
};

std::unordered_map<Point, int, HashPoint> 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使用方法的详细内容,更多请关注php中文网其它相关文章!

c++速学教程(入门到精通)
c++速学教程(入门到精通)

c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号