【C++】无序容器unordered_set和unordered_map的使用

1. unordered_set系列的使用

1.1 unordered_set和unordered_multiset参考文档

https://legacy.cplusplus.com/reference/unordered_set/

1.2 unordered_set类的介绍

unordered_set底层是哈希表,而set底层是红黑树

1.3 unordered_set和set的使用差异

cpp 复制代码
void test_set2()
{
	const size_t N = 1000000;
	unordered_set<int> us;
	set<int> s;
	vector<int> v;
	v.reserve(N);
	srand(time(0));
	for (size_t i = 0; i < N; ++i)
	{
		//v.push_back(rand()); // N比较大时,重复值比较多
		v.push_back(rand() + i); // 重复值相对少
		//sv.push_back(i); // 没有重复,有序
	}

	size_t begin1 = clock();
	for (auto e : v)
	{
		s.insert(e);
	}
	size_t end1 = clock();
	cout << "set insert:" << end1 - begin1 << endl;
	size_t begin2 = clock();
	us.reserve(N);
	for (auto e : v)
	{
		us.insert(e);
	}
	size_t end2 = clock();
	cout << "unordered_set insert:" << end2 - begin2 << endl;

	int m1 = 0;
	size_t begin3 = clock();
	for (auto e : v)
	{
		auto ret = s.find(e);
		if (ret != s.end())
		{
			++m1;
		}
	}

	size_t end3 = clock();
	cout << "set find:" << end3 - begin3 << "->" << m1 << endl;
	int m2 = 0;
	size_t begin4 = clock();
	for (auto e : v)
	{
		auto ret = us.find(e);
		if (ret != us.end())
		{
			++m2;
		}
	}
	size_t end4 = clock();
	cout << "unorered_set find:" << end4 - begin4 << "->" << m2 << endl;
	cout << "插入数据个数:" << s.size() << endl;
	cout << "插入数据个数:" << us.size() << endl << endl;

	size_t begin5 = clock();
	for (auto e : v)
	{
		s.erase(e);
	}
	size_t end5 = clock();
	cout << "set erase:" << end5 - begin5 << endl;

	size_t begin6 = clock();
	for (auto e : v)
	{
		us.erase(e);
	}
	size_t end6 = clock();
	cout << "unordered_set erase:" << end6 - begin6 << endl << endl;
}

1.4 unordered_map和map的使用差异

1.5 unordered_multimap/unordered_multiset

  • unordered_multimap/unordered_multiset跟multimap/multiset功能完全类似,⽀持Key冗余。
  • unordered_multimap/unordered_multiset跟multimap/multiset的差异也是三个⽅面的差异,
    key的要求的差异,iterator及遍历顺序的差异,性能的差异。

1.6 unordered_xxx的哈希相关接口

Buckets和Hash policy系列的接⼝分别是跟哈希桶和负载因⼦相关的接口,⽇常使用的角度我们不需要太关注,后⾯学习了哈希表底层,我们再来看这个系列的接⼝,一目了然。

1.7 相关算法题

884. 两句话中的不常见单词 - 力扣(LeetCode)

相关推荐
阿旭超级学得完4 分钟前
C++11包装器(function和bind)
java·开发语言·c++·算法·哈希算法·散列表
輕華4 分钟前
uv工具详解——Python包与项目管理器完全指南
开发语言·python·uv
li星野6 分钟前
位运算 & 数学 & 高频进阶九题通关(Python + C++)
c++·python·学习·算法
念何架构之路26 分钟前
Go语言常见并发模式
开发语言·后端·golang
磊 子1 小时前
多态类原理+四种类型转换+异常处理
开发语言·c++·算法
脆皮炸鸡7551 小时前
库制作与原理~动态链接
linux·开发语言·经验分享·笔记·学习方法
XMYX-01 小时前
26 - Go recover 捕获错误:优雅恢复的真正意义
开发语言·golang
王老师青少年编程1 小时前
csp信奥赛C++高频考点专项训练之字符串 --【回文字符串】:回文拼接
c++·字符串·csp·高频考点·信奥赛·字符串回文·回文拼接
小白学大数据1 小时前
基于大模型的Python智能爬虫:语义识别与数据清洗实践
开发语言·爬虫·python·数据分析