unordered_set 的使用方法

本文主要写法参考C++ STL 函数库

std::unordered_set(C++11)

unordered_set 是一种关联容器,set 和 map 内部实现是基于 RedBlackTree,unordered_set 和 unordered_map 是基于 Hashtable。红黑树有序,而哈希表无序。

特性

  1. 不再以键值对的形式存储数据,而是直接存储数据的值(只有一个值!)
  2. 容器内部存储的各个元素的值都互不相等,且不能被修改
  3. 不会对内部存储的数据进行排序

模板

1
2
3
4
5
6
7
template < class Key,                        // unordered_set::key_type/value_type
class Hash = hash<Key>, // unordered_set::hasher
class Pred = equal_to<Key>, // unordered_set::key_equal
class Alloc = allocator<Key> // unordered_set::allocator_type
> class unordered_set;
//一般定义使用
unordered_set<T> ans;

迭代器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//返回头迭代器 begin()
unordered_set<int>::iterator it_begin = ans.begin();

//返回尾迭代器 end()
unordered_set<int>::iterator it_end = ans.end();

//返回const头迭代器 cbegin()
unordered_set<int>::const_iterator const_it_begin = ans.cbegin();

//返回const尾迭代器 cend()
unordered_set<int>::const_iterator const_it_end = ans.cend();

//槽迭代器
unordered_set<int>::local_iterator local_iter_begin = ans.begin(1);

unordered_set<int>::local_iterator local_iter_end = ans.end(1);

一般操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
//查找函数 find() 通过给定主键查找元素
unordered_set<int>::iterator find_iter = ans.find(1);

//value出现的次数 count() 返回匹配给定主键的元素的个数
ans.count(1);

//返回元素在哪个区域equal_range() 返回值匹配给定搜索值的元素组成的范围
pair<unordered_set<int>::iterator, unordered_set<int>::iterator>
pair_equal_range = ans.equal_range(1);

//插入函数 emplace()
ans.emplace(1);

//插入函数 emplace_hint() 使用迭代器
ans.emplace_hint(ite_begin, 1);

//插入函数 insert()
ans.insert(1);

//删除 erase()
ans.erase(1);//1.迭代器 value 区域

//清空 clear()
ans.clear();

//交换 swap(),括号内可接另外一个unordered_set
ans.swap();

//判断是否为空
ans.empty();

//获取元素个数 size()
ans.size();

//获取最大存储量 max_size()
ans.max_size();

//篮子操作 篮子个数 bucket_count() 返回槽(Bucket)数
ans.bucket_count();

//篮子最大数量 max_bucket_count() 返回最大槽数
ans.max_bucket_count();

//篮子个数 bucket_size() 返回槽大小
ans.bucket_size(3);

//返回篮子 bucket() 返回元素所在槽的序号
ans.bucket(1);

//load_factor 返回载入因子,即一个元素槽(Bucket)的最大元素数
ans.load_factor();

//max_load_factor 返回或设置最大载入因子
ans.max_load_factor();

//rehash 设置槽数
ans.rehash(1);

//reserve请求改变容器容量
ans.reserve(1000);

//hash_function() 返回与hash_func相同功能的函数指针
auto hash_func_test = ans.hash_function();

//key_eq() 返回比较key值得函数指针
auto key_eq_test = ans.key_eq()

基本上以上就是全部使用的方法


unordered_set 的使用方法
https://chaggle.github.io/2021/01/07/cpp/unordered_set/
作者
chaggle
发布于
2021年1月7日
许可协议