行业知识
C++总结(7):STL无序容器之unordered
2026-11-17 11:57:57
来源:互联网转载
前两节介���了STL中的顺序容器和关联容器,本节来介绍一下无序容器。无序容器与关联容器类似,但是关联容器是顺序排序的,而无序容器实现了未排序(哈希)的数据结构。
()文章目录
- 1 unordered_set
- 2 unordered_map
- 3 unordered_multiset
- 4 unordered_multimap
1 unordered_set
无序集合(unordered_set)是一种使用哈希表实现的无序关联容器,其中键被哈希到哈希表的索引位置,因此插入操作总是随机的。无序集合上的所有操作在平均情况下都具有常数时间复杂度O(1),但在最坏情况下,时间复杂度可以达到线性时间O(n),这取决于内部使用的哈希函数,但实际上它们表现非常出色,通常提供常数时间的查找操作。
无序集合可以包含任何类型的键 - 预定义或用户自定义数据结构,但所有键必须是唯一的。它的语法如下:
()std::unordered_set name;
常用方法
- size()和empty():用于获取大小和集合是否为空
- find():用于查找键
- insert()和erase():用于插入和删除元素
#include using namespace std;int main(){unordered_set stringSet;stringSet.insert("code");stringSet.insert("in");stringSet.insert("c++");stringSet.insert("is");stringSet.insert("fast");string key = "slow";if (stringSet.find(key) == stringSet.end())cout
上一篇:服务器未备份怎么恢复?