c++中 unordered_map 与 unordered_set 用法指南

2024-06-02 03:28

本文主要是介绍c++中 unordered_map 与 unordered_set 用法指南,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

unordered_map 与 unordered_set 区别与联系

unordered_mapunordered_set 都是 C++ 标准模板库(STL)中的容器,它们使用哈希表作为底层数据结构,提供了快速的查找、插入和删除操作。下面是它们之间的联系与区别:

联系

  1. 底层实现:两者都基于哈希表实现,利用了哈希函数来分布元素。
  2. 性能特点:它们都提供平均时间复杂度为 O(1) 的查找、插入和删除操作。
  3. 冲突解决:两者都使用某种形式的链表或红黑树来解决哈希冲突。
  4. 非线性容器:它们都是非线性容器,不保证元素的顺序。

区别

  1. 存储内容

    • unordered_map 存储键值对,即每个元素包含一个键(key)和一个值(value),键是唯一的。
    • unordered_set 只存储唯一的值,不包含键。
  2. 用途

    • unordered_map 适用于需要通过键来访问或存储数据的场景,类似于关联数组或字典。
    • unordered_set 适用于需要存储唯一元素集合的场景,类似于集合。
  3. 操作

    • unordered_map 支持通过键来访问、插入、删除和查找值。
    • unordered_set 支持插入、删除和查找元素。
  4. 内存使用

    • unordered_map 由于需要存储键和值,通常比 unordered_set 使用更多的内存。
  5. 迭代器

    • unordered_map 的迭代器可以解引用为一个 pair,其中包含键和值。
    • unordered_set 的迭代器只能解引用为一个值。
  6. 示例
    在这里插入图片描述

  7. 元素查找

    • unordered_mapfind 方法返回一个迭代器,指向键值对,可以访问键和值。
    • unordered_setfind 方法返回一个迭代器,指向集合中的元素。

使用场景

  • 当你需要一个键来快速访问数据时,使用 unordered_map
  • 当你只需要存储一组不包含重复元素的数据时,使用 unordered_set

总的来说,unordered_mapunordered_set 在实现上有很多相似之处,但它们服务于不同的数据存储需求。选择使用哪一个取决于你的具体应用场景和需求。

unordered_map

unordered_map 是 C++ 中的一个关联容器,它存储了键值对,并且提供了快速的数据访问能力。

  1. 基本使用
#include <iostream>
#include <unordered_map>int main() {std::unordered_map<int, std::string> umap;umap[1] = "one";umap[2] = "two";umap[3] = "three";// 打印所有键值对for (const auto& pair : umap) {std::cout << pair.first << ": " << pair.second << std::endl;}
}
  • 输出结果:

1: one
2: two
3: three
在这里插入图片描述

  1. 初始化列表
#include <iostream>
#include <unordered_map>int main() {std::unordered_map<int, std::string> umap = {{1, "one"},{2, "two"},{3, "three"}};// 打印所有键值对for (const auto& pair : umap) {std::cout << pair.first << ": " << pair.second << std::endl;}
}
  • 输出结果:

1: one
2: two
3: three
在这里插入图片描述

  1. 访问元素
#include <iostream>
#include <unordered_map>int main() {std::unordered_map<int, std::string> umap = {{1, "one"},{2, "two"}};// 访问元素std::cout << "Value for key 1: " << umap[1] << std::endl;// 访问不存在的键将自动插入该键,并为其分配一个默认值std::cout << "Value for key 3: " << umap[3] << std::endl; // 默认值,例如空字符串
}
  • 输出结果:

Value for key 1: one
Value for key 3:
在这里插入图片描述

  1. 检查键是否存在
#include <iostream>
#include <unordered_map>int main() {std::unordered_map<int, std::string> umap = {{1, "one"},{2, "two"}};int key = 1;if (umap.find(key) != umap.end()) {std::cout << "Key " << key << " exists." << std::endl;}else {std::cout << "Key " << key << " does not exist." << std::endl;}
}
  • 输出结果:

Key 1 exists.
在这里插入图片描述

  1. 删除元素
#include <iostream>
#include <unordered_map>int main() {std::unordered_map<int, std::string> umap = {{1, "one"},{2, "two"}};int keyToRemove = 1;auto it = umap.find(keyToRemove);if (it != umap.end()) {umap.erase(it);}// 打印删除元素后的映射for (const auto& pair : umap) {std::cout << pair.first << ": " << pair.second << std::endl;}
}
  • 输出结果:

2: two
在这里插入图片描述

  1. 使用 emplace 插入元素
#include <iostream>
#include <unordered_map>int main() {std::unordered_map<int, std::string> umap;// 使用 emplace 插入元素auto result = umap.emplace(1, "one");if (result.second) {std::cout << "Insert successful." << std::endl;}// 尝试再次插入相同的键result = umap.emplace(1, "uno");if (!result.second) {std::cout << "Insert failed, key already exists." << std::endl;}// 打印映射for (const auto& pair : umap) {std::cout << pair.first << ": " << pair.second << std::endl;}
}
  • 输出结果:

Insert successful.
Insert failed, key already exists.
1: one
在这里插入图片描述

  1. 遍历 unordered_map
#include <iostream>
#include <unordered_map>int main() {std::unordered_map<int, std::string> umap = {{1, "one"},{2, "two"},{3, "three"}};// 使用范围 for 循环遍历for (const auto& pair : umap) {std::cout << pair.first << ": " << pair.second << std::endl;}// 使用迭代器遍历for (auto it = umap.begin(); it != umap.end(); ++it) {std::cout << it->first << ": " << it->second << std::endl;}
}
  • 输出结果:

1: one
2: two
3: three
1: one
2: two
3: three
在这里插入图片描述

  1. 使用 unordered_map 的 size 和 empty
#include <iostream>
#include <unordered_map>int main() {std::unordered_map<int, std::string> umap = {{1, "one"},{2, "two"}};std::cout << "Size of umap: " << umap.size() << std::endl;std::cout << "Is umap empty? " << (umap.empty() ? "Yes" : "No") << std::endl;
}
  • 输出结果:

Size of umap: 2
Is umap empty? No
在这里插入图片描述

unordered_set

  1. 基本使用
#include <iostream>
#include <unordered_set>int main() {std::unordered_set<int> uset;uset.insert(10);uset.insert(20);uset.insert(30);std::cout << "Size of uset: " << uset.size() << std::endl;
}
  • 输出结果:

Size of uset: 3
在这里插入图片描述

  1. 初始化列表
#include <iostream>
#include <unordered_set>int main() {std::unordered_set<int> uset = { 10, 20, 30, 40, 50 };for (int num : uset) {std::cout << num << " ";}std::cout << std::endl;
}
  • 输出结果:

50 10 20 30 40
在这里插入图片描述

  1. 检查元素是否存在
#include <iostream>
#include <unordered_set>int main() {std::unordered_set<int> uset = { 1, 2, 3 };int key = 2;if (uset.find(key) != uset.end()) {std::cout << "Element " << key << " exists in uset." << std::endl;}else {std::cout << "Element " << key << " does not exist in uset." << std::endl;}
}
  • 输出结果:

Element 2 exists in uset.
在这里插入图片描述

  1. 删除元素
#include <iostream>
#include <unordered_set>int main() {std::unordered_set<int> uset = { 1, 2, 3 };int keyToRemove = 2;if (uset.erase(keyToRemove)) {std::cout << "Element removed from uset." << std::endl;}else {std::cout << "Element not found in uset." << std::endl;}for (int num : uset) {std::cout << num << " ";}std::cout << std::endl;
}
  • 输出结果:

Element removed from uset.
1 3
在这里插入图片描述

  1. 使用 emplace 插入元素
#include <iostream>
#include <unordered_set>int main() {std::unordered_set<int> uset;// 使用 emplace 插入元素auto result = uset.emplace(10);if (result.second) {std::cout << "Insert successful." << std::endl;}// 尝试再次插入相同的元素result = uset.emplace(10);if (!result.second) {std::cout << "Insert failed, element already exists." << std::endl;}
}
  • 输出结果:

Insert successful.
Insert failed, element already exists.
在这里插入图片描述

  1. 遍历 unordered_set
#include <iostream>
#include <unordered_set>int main() {std::unordered_set<int> uset = { 5, 10, 15, 20, 25 };// 使用范围 for 循环遍历for (int num : uset) {std::cout << num << " ";}std::cout << std::endl;// 使用迭代器遍历for (auto it = uset.begin(); it != uset.end(); ++it) {std::cout << *it << " ";}std::cout << std::endl;
}
  • 输出结果:

5 10 15 20 25
5 10 15 20 25
在这里插入图片描述

  1. 使用 unordered_set 的 size 和 empty
#include <iostream>
#include <unordered_set>int main() {std::unordered_set<int> uset = { 1, 2, 3 };std::cout << "Size of uset: " << uset.size() << std::endl;std::cout << "Is uset empty? " << (uset.empty() ? "Yes" : "No") << std::endl;
}
  • 输出结果:

Size of uset: 3
Is uset empty? No
在这里插入图片描述

  1. 清空 unordered_set
#include <iostream>
#include <unordered_set>int main() {std::unordered_set<int> uset = { 1, 2, 3, 4, 5 };uset.clear(); // 清空 usetstd::cout << "Is uset empty after clear? " << (uset.empty() ? "Yes" : "No") << std::endl;
}
  • 输出结果:

Is uset empty after clear? Yes
在这里插入图片描述

  1. 自定义哈希函数
#include <iostream>
#include <unordered_set>// 自定义哈希函数
struct custom_hash {std::size_t operator()(int x) const {return std::hash<int>()(x);}
};int main() {std::unordered_set<int, custom_hash> uset = { 1, 2, 3 };for (int num : uset) {std::cout << num << " ";}std::cout << std::endl;
}
  • 输出结果:

1 2 3
在这里插入图片描述

这篇关于c++中 unordered_map 与 unordered_set 用法指南的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1022902

相关文章

关于C++中的虚拟继承的一些总结(虚拟继承,覆盖,派生,隐藏)

1.为什么要引入虚拟继承 虚拟继承是多重继承中特有的概念。虚拟基类是为解决多重继承而出现的。如:类D继承自类B1、B2,而类B1、B2都继承自类A,因此在类D中两次出现类A中的变量和函数。为了节省内存空间,可以将B1、B2对A的继承定义为虚拟继承,而A就成了虚拟基类。实现的代码如下: class A class B1:public virtual A; class B2:pu

C++对象布局及多态实现探索之内存布局(整理的很多链接)

本文通过观察对象的内存布局,跟踪函数调用的汇编代码。分析了C++对象内存的布局情况,虚函数的执行方式,以及虚继承,等等 文章链接:http://dev.yesky.com/254/2191254.shtml      论C/C++函数间动态内存的传递 (2005-07-30)   当你涉及到C/C++的核心编程的时候,你会无止境地与内存管理打交道。 文章链接:http://dev.yesky

C++的模板(八):子系统

平常所见的大部分模板代码,模板所传的参数类型,到了模板里面,或实例化为对象,或嵌入模板内部结构中,或在模板内又派生了子类。不管怎样,最终他们在模板内,直接或间接,都实例化成对象了。 但这不是唯一的用法。试想一下。如果在模板内限制调用参数类型的构造函数会发生什么?参数类的对象在模板内无法构造。他们只能从模板的成员函数传入。模板不保存这些对象或者只保存他们的指针。因为构造函数被分离,这些指针在模板外

C++工程编译链接错误汇总VisualStudio

目录 一些小的知识点 make工具 可以使用windows下的事件查看器崩溃的地方 dumpbin工具查看dll是32位还是64位的 _MSC_VER .cc 和.cpp 【VC++目录中的包含目录】 vs 【C/C++常规中的附加包含目录】——头文件所在目录如何怎么添加,添加了以后搜索头文件就会到这些个路径下搜索了 include<> 和 include"" WinMain 和

C/C++的编译和链接过程

目录 从源文件生成可执行文件(书中第2章) 1.Preprocessing预处理——预处理器cpp 2.Compilation编译——编译器cll ps:vs中优化选项设置 3.Assembly汇编——汇编器as ps:vs中汇编输出文件设置 4.Linking链接——链接器ld 符号 模块,库 链接过程——链接器 链接过程 1.简单链接的例子 2.链接过程 3.地址和

C++必修:模版的入门到实践

✨✨ 欢迎大家来到贝蒂大讲堂✨✨ 🎈🎈养成好习惯,先赞后看哦~🎈🎈 所属专栏:C++学习 贝蒂的主页:Betty’s blog 1. 泛型编程 首先让我们来思考一个问题,如何实现一个交换函数? void swap(int& x, int& y){int tmp = x;x = y;y = tmp;} 相信大家很快就能写出上面这段代码,但是如果要求这个交换函数支持字符型

C++入门01

1、.h和.cpp 源文件 (.cpp)源文件是C++程序的实际实现代码文件,其中包含了具体的函数和类的定义、实现以及其他相关的代码。主要特点如下:实现代码: 源文件中包含了函数、类的具体实现代码,用于实现程序的功能。编译单元: 源文件通常是一个编译单元,即单独编译的基本单位。每个源文件都会经过编译器的处理,生成对应的目标文件。包含头文件: 源文件可以通过#include指令引入头文件,以使

C++面试八股文:std::deque用过吗?

100编程书屋_孔夫子旧书网 某日二师兄参加XXX科技公司的C++工程师开发岗位第26面: 面试官:deque用过吗? 二师兄:说实话,很少用,基本没用过。 面试官:为什么? 二师兄:因为使用它的场景很少,大部分需要性能、且需要自动扩容的时候使用vector,需要随机插入和删除的时候可以使用list。 面试官:那你知道STL中的stack是如何实现的吗? 二师兄:默认情况下,stack使

剑指offer(C++)--孩子们的游戏(圆圈中最后剩下的数)

题目 每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此。HF作为牛客的资深元老,自然也准备了一些小游戏。其中,有个游戏是这样的:首先,让小朋友们围成一个大圈。然后,他随机指定一个数m,让编号为0的小朋友开始报数。每次喊到m-1的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物,并且不再回到圈中,从他的下一个小朋友开始,继续0...m-1报数....这样下去

剑指offer(C++)--扑克牌顺子

题目 LL今天心情特别好,因为他去买了一副扑克牌,发现里面居然有2个大王,2个小王(一副牌原本是54张^_^)...他随机从中抽出了5张牌,想测测自己的手气,看看能不能抽到顺子,如果抽到的话,他决定去买体育彩票,嘿嘿!!“红心A,黑桃3,小王,大王,方片5”,“Oh My God!”不是顺子.....LL不高兴了,他想了想,决定大\小 王可以看成任何数字,并且A看作1,J为11,Q为1