前两节介绍了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
文章版权声明:除非注明,否则均为VPS857原创文章,转载或复制请以超链接形式并注明出处。
还没有评论,来说两句吧...