赞
踩
在C++98中,STL提供了底层为红黑树结构的一系列关联式容器,在查询时效率可达到
l
o
g
2
N
log_2 N
log2N,即最差情况下需要比较红黑树的高度次,当树中的节点非常多时,查询效率也不理想。最好的查询是,进行很少的比较次数就能够将元素找到,因此在C++11中,STL又提供了4个unordered
系列的关联式容器,这四个容器与红黑树结构的关联式容器使用方式基本类似,只是其底层结构不同
还有俩:unordered_multimap
/unordered_multiset
,本文不做介绍
底层是哈希表,迭代器遍历是无序的,是单向迭代器
其他的用法和map,set没有什么区别
函数声明 | 功能介绍 |
---|---|
bool empty()const | 检测是否为空 |
size_t size()const | 获取有效元素个数 |
begin | 返回第一个元素的迭代器 |
end | 返回最后一个元素的下一个位置的迭代器 |
cbegin | 返回第一个元素的const迭代器 |
cend | 返回最后一个元素的下一个位置的const迭代器 |
operator[] | 返回与key对应的value,没有一个默认值 |
iterator find(const K& key) | 返回key在哈希桶中的位置 |
size_t count(const K& key) | 返回哈希桶中关键码伪key的键值对的个数 |
insert | 向容器中插入键值对 |
erase | 删除容器中的键值对 |
void clear() | 清空容器中有效元素个数 |
void swap(unordered_map &) | 交换两个容器中的元素 |
size_t bucket_count()const | 返回哈希桶中桶的总个数 |
size_t bucket_size(size_t n)const | 返回n号桶中有效元素的总个数 |
size_t bucket(const K& key) | 返回元素key所在的桶号 |
unordered系列的关联式容器之所以效率比较高,是因为其底层使用了哈希结构。
简单来说:key和存储位置建立一个对应关系
顺序结构以及平衡树中,元素关键码与其存储位置之间没有对应的关系,因此在查找一个元素时,必须要经过关键码的多次比较。顺序查找时间复杂度为O(N),平衡树中为树的高度,即O(
l
o
g
2
N
log_2 N
log2N),搜索的效率取决于搜索过程中元素的比较次数。
理想的搜索方法:可以不经过任何比较,一次直接从表中得到要搜索的元素。
如果构造一种存储结构,通过某种函数(hashFunc)使元素的存储位置与它的关键码之间能够建立一一映射的关系,那么在查找时通过该函数可以很快找到该元素.
当向该结构中:
hash(key) = key % capacity
; capacity为存储元素底层空间总的大小用该方法进行搜索不必进行多次关键码的比较,因此搜索的速度比较快
问题:按照上述哈希方式,向集合中插入元素44,会出现什么问题?
会出现哈希冲突!
对于两个数据元素的关键字
k
i
k_i
ki和
k
j
k_j
kj(i != j),有
k
i
k_i
ki !=
k
j
k_j
kj,但有:Hash(
k
i
k_i
ki) == Hash(
k
j
k_j
kj),即:不同关键字通过相同哈希哈数计算出相同的哈希地址,该种现象称为哈希冲突或哈希碰撞
把具有不同关键码而具有相同哈希地址的数据元素称为“同义词”
哈希冲突只能尽可能避免,很难完全解决:
引起哈希冲突的一个原因可能是:哈希函数设计不够合理。
直接定址法–(常用)
取关键字的某个线性函数为散列地址:Hash(Key)= A*Key + B
优点:简单、均匀
缺点:需要事先知道关键字的分布情况
使用场景:适合查找比较小且连续的情况
除留余数法–(常用)
设散列表中允许的地址数为m,取一个不大于m,但最接近或者等于m的质数p作为除数,按照哈希函数:Hash(key) = key% p(p<=m)
,将关键码转换成哈希地址
平方取中法–(了解)
假设关键字为1234,对它平方就是1522756,抽取中间的3位227作为哈希地址;再比如关键字为4321,对它平方就是18671041,抽取中间的3位671(或710)作为哈希地址
平方取中法比较适合:不知道关键字的分布,而位数又不是很大的情况
折叠法–(了解)
折叠法是将关键字从左到右分割成位数相等的几部分(最后一部分位数可以短些),然后将这几部分叠加求和,并按散列表表长,取后几位作为散列地址。
折叠法适合事先不需要知道关键字的分布,适合关键字位数比较多的情况
随机数法–(了解)
选择一个随机函数,取关键字的随机函数值为它的哈希地址,即H(key) = random(key),其中
random为随机数函数。
通常应用于关键字长度不等时采用此法
数学分析法–(了解)
设有n个d位数,每一位可能有r种不同的符号,这r种不同的符号在各位上出现的频率不一定
相同,可能在某些位上分布比较均匀,每种符号出现的机会均等,在某些位上分布不均匀只
有某几种符号经常出现。可根据散列表的大小,选择其中各种符号分布均匀的若干位作为散
列地址。例如:
假设要存储某家公司员工登记表,如果用手机号作为关键字,那么极有可能前7位都是相同的,那么我们可以选择后面的四位作为散列地址,如果这样的抽取工作还容易出现 冲突,还可以对抽取出来的数字进行反转(如1234改成4321)、右环位移(如1234改成4123)、左环移位、前两数与后两数叠加(如1234改成12+34=46)等方法
数字分析法通常适合处理关键字位数比较大的情况,并且事先知道关键字的分布且关键字的若干位分布较均匀的情况
注意:哈希函数设计的越精妙,产生哈希冲突的可能性就越低,但是无法避免哈希冲突
解决哈希冲突两种常见的方法是:闭散列和开散列
闭散列:也叫开放定址法,当发生哈希冲突时,如果哈希表未被装满,说明在哈希表中必然还有空位置,那么可以把key存放到冲突位置中的“下一个” 空位置中去。那如何寻找下一个空位置呢?
比如2.1中的场景,现在需要插入元素44,先通过哈希函数计算哈希地址,hashAddr为4,因此44理论上应该插在该位置,但是该位置已经放了值为4的元素,即发生哈希冲突。
线性探测:从发生冲突的位置开始,依次向后探测,直到寻找到下一个空位置为止。
我们查找是一直查到表为空为止,如果使用真删除的方法,就会导致还没有查找完就提前结束了
// 哈希表每个空间给个标记
// EMPTY此位置空, EXIST此位置已经有元素, DELETE元素已经删除
enum State
{
EMPTY,
EXIST,
DELETE
};
线性探测优点:实现非常简单,
线性探测缺点:一旦发生哈希冲突,所有的冲突连在一起,容易产生数据“堆积”,即:不同关键码占据了可利用的空位置,使得寻找某关键码的位置需要许多次比较,导致搜索效率降低。我们可以使用’二次探测’等方法缓解
线性探测的缺陷是产生冲突的数据堆积在一块,这与其找下一个空位置有关系,因为找空位置的方式就是挨着往后逐个去找,因此二次探测为了避免该问题,找下一个空位置的方法为:
H
i
H_i
Hi = (
H
0
H_0
H0 +
i
2
i^2
i2 )% m, 或者:
H
i
H_i
Hi = (
H
0
H_0
H0 -
i
2
i^2
i2 )% m。其中:i = 1,2,3…,
H
0
H_0
H0是通过散列函数Hash(x)对元素的关键码 key 进行计算得到的位置,m是表的大小。
对于2.1中如果要插入44,产生冲突,使用解决后的情况为
研究表明:当表的长度为质数且表装载因子a不超过0.5时,新的表项一定能够插入,而且任何一个位置都不会被探查两次。因此只要表中有一半的空位置,就不会存在表满的问题。在搜索时可以不考虑表装满的情况,但在插入时必须确保表的装载因子a不超过0.5,如果超出必须考虑增容
因此:散列最大的缺陷就是空间利用率比较低,这也是哈希的缺陷
从上图可以看出,开散列中每个桶中放的都是发生哈希冲突的元素
#define _CRT_SECURE_NO_WARNINGS 1 #pragma once #include<vector> namespace OpenAdress { enum State//设置节点的三种状态-伪删除法 { EMPTY, EXIST, DELETE }; template<class K, class V> struct HashData//存放节点数据和状态 { pair<K, V> _kv; State _state = EMPTY; }; template<class K, class V> class HashTable { public: bool insert(const pair<K, V>& kv) { } HashData<K, V>* Find(const K& key) { } bool Erase(const K& key) { } private: vector<HashData<K, V>> _tables;//哈希表依赖于vector size_t _n = 0;//存储的有效数据个数,默认为0,一定要加这个默认值 }; }
插入会涉及到扩容
扩容会有一个负载因子
的概念
//此处我们设置负载因子不超过0.7 //检查负载因子,看是否需要扩容 //这里乘十是因为整形除以整形还是整形,会导致死循环 //也可以强制类型转换: if((double)_n / (double) _tables.size() >= 0.7) if (_tables.size() == 0 || 10 * (_n) / _tables.size() >= 7) { //第一种方法:遍历旧表,重新映射到新表 //扩容的时候一定要考虑size为0的情况,否则会死循环 size_t newsize = _tables.size() == 0 ? 10 : _tables.size() * 2; vector<HashData<K, V>> newtables;//创建新表 //遍历旧表,重新映射: for (auto& data : _tables) { if (data._state == EXIST) { size_t i = 1; //计算hashi size_t hashi = data._kv.first % newtables.size(); size_t index = hashi; while (newtables[index]._state == EXIST) { index = hashi + i; //这里是防止一直没有找到 index %= newtables.size(); ++i; } newtable[index]._kv = data._kv; newtable[index]._state = EXIST; } } }
我们可以复用insert
if (_tables.size() == 0 || 10 * (_n) / _tables.size() >= 7)
{
size_t newsize = _tables.size() == 0 ? 10 : _tables.size() * 2;
HashTable<K, V> newht;
newht._tables.resize(newsize);
for (auto& data : _tables)//这里遍历的是每一个节点!
{
if (data._state == EXIST)
{
newht.insert(data._kv);
}
}
_tables.swap(newht._tables);
}
bool insert(const pair<K, V>& kv) { if (Find(kv.first)) { return false; } if (_tables.size() == 0 || 10 * (_n) / _tables.size() >= 7) { size_t newsize = _tables.size() == 0 ? 10 : _tables.size() * 2; HashTable<K, V> newht; newht._tables.resize(newsize); for (auto& data : _tables) { if (data._state == EXIST) { newht.insert(data._kv); } } _tables.swap(newht._tables); } size_t hashi = kv.first % _tables.size(); size_t i = 1; size_t index = hashi; while (_tables[index]._state == EXIST) { index = hashi + i; index = index % _tables.size(); ++i; } _tables[index]._kv = kv; _tables[index]._state = EXIST; ++_n; return true; }
HashData<K, V>* Find(const K& key) { if (_tables.size() == 0) { return nullptr; } size_t hashi = key % _tables.size(); size_t i = 1; size_t index = hashi; while (_tables[index]._state != EMPTY) { if (_tables[index]._state == EXIST && _tables[index]._kv.first == key) { return _tables[index]._kv; } index = hashi + i; index %= _tables.size(); ++i; //如果已经找了一圈,那么说明全是存在+删除 if (index == hashi) { break; } } return nullptr; }
bool Erase(const K& key)
{
//先找到key对应的地址
HashData<K, V>* ret = Find(key);
if (ret)
{
ret->_state = DELETE;
--_n;
return true;
}
else
{
return false;
}
}
简单来说,就是通过find找到KV地址,然后修改状态,_n--
即可
#define _CRT_SECURE_NO_WARNINGS 1 #pragma once #include<vector> namespace OpenAdress { enum State//设置节点的三种状态-伪删除法 { EMPTY, EXIST, DELETE }; template<class K, class V> struct HashData//存放节点数据和状态 { pair<K, V> _kv; State _state = EMPTY; }; template<class K, class V> class HashTable { public: bool insert(const pair<K, V>& kv) { //如果插入的数据已经存在,则返回false if (Find(kv.first))//找到了 { return false; } //检查负载因子(我们这里设置为0.7),看是否需要扩容 //这里乘十是因为整形除以整形还是整形,会导致死循环 //if((double)_n / (double) _tables.size() >= 0.7) if (_tables.size() == 0 || 10 * (_n) / _tables.size() >= 7) { size_t newsize = _tables.size() == 0 ? 10 : _tables.size() * 2; HashTable<K, V> newht; newht._tables.resize(newsize); //遍历旧表,重新得到新表 for (auto& data : _tables) { if (data._state == EXIST) { newht.insert(data._kv); } } _tables.swap(newht._tables); } size_t hashi = kv.first % _tables.size(); //线性探测 size_t i = 1; size_t index = hashi; while (_tables[index]._state == EXIST) { index = hashi + i; index = index % _tables.size(); ++i; } _tables[index]._kv = kv; _tables[index]._state = EXIST; ++_n; return true; } HashData<K, V>* Find(const K& key) { if (_tables.size() == 0) { return nullptr; } size_t hashi = key % _tables.size(); size_t i = 1; size_t index = hashi; while (_tables[index]._state != EMPTY) { if (_tables[index]._state == EXIST && _tables[index]._kv.first == key) { return _tables[index]._kv; } index = hashi + i; index %= _tables.size(); ++i; //如果已经找了一圈,那么说明全是存在+删除 if (index == hashi) { break; } } return nullptr; } bool Erase(const K& key) { //先找到key对应的地址 HashData<K, V>* ret = Find(key); if (ret) { ret->_state = DELETE; --_n; return true; } else { return false; } } private: vector<HashData<K, V>> _tables;//哈希表依赖于vector size_t _n = 0;//存储的有效数据个数,默认为0,一定要加这个默认值 }; }
namespace HashBucket { template<class K, class V> struct HashNode { HashNode<K, V>* _next; pair<K, V> _kv; //写一个默认构造,后面会用到 HashNode(const pair<K, V>& kv) :_next(nullptr), kv(_kv) {} }; template<class K, class V> class HashTable { typedef HashNode<K,V> Node; public: ~HashTable() { for (auto& cur : _tables) { while (cur) { Node* next = cur->next; delete cur; cur = next; } cur = nullptr; } } Node* Find(const K& key) { } bool Erase(const K& key) { } bool insert(const pair<K, V>& kv) { } private: vector<Node*> _tables; size_t _n = 0; }; }
Node* Find(const K& key) { if (_tables.size() == 0) { return nullptr; } size_t hashi = key % _tables.size(); Node* cur = _tables[hashi]; while (cur) { if (cur._kv.first == key) { return cur; } cur = cur->_next; } return nullptr; }
bool Erase(const K& key) { if (_tables.size() == 0) { return false; } size_t hashi = key % _tables.size(); Node* cur = _tables[hashi]; Node* prev = nullptr; while (cur) { if (cur._kv.first == key) { if (prev == nullptr) { _tables[hashi] = cur->_next; } else { prev->_next = cur->_next; } delete cur; return true; } else { prev = cur; cur = cur->_next; } } return false; }
bool insert(const pair<K, V>& kv) { if (_tables.size() == 0) { return false; } //负载因子为1时扩容 if (_n == _tables.size()) { size_t newsize = _tables.size() == 0 ? 10 : _tables.size() * 2; //记得全部置为nullptr! vector<Node*> newtables(newsize, nullptr); for (auto& cur : _tables) { while (cur) { Node* next = cur->next; size_t hashi = cur._kv.first % newtables.size(); //头插到新表 cur->next = newtables[hashi]; newtables[hashi] = cur; cur = next; } } _tables.swap(newtables); } }
namespace HashBucket { template<class K, class V> struct HashNode { HashNode<K, V>* _next; pair<K, V> _kv; //写一个默认构造,后面会用到 HashNode(const pair<K, V>& kv) :_next(nullptr), kv(_kv) {} }; template<class K, class V> class HashTable { typedef HashNode<K,V> Node; public: ~HashTable() { for (auto& cur : _tables) { while (cur) { Node* next = cur->next; delete cur; cur = next; } cur = nullptr; } } Node* Find(const K& key) { if (_tables.size() == 0) { return nullptr; } size_t hashi = key % _tables.size(); Node* cur = _tables[hashi]; while (cur) { if (cur._kv.first == key) { return cur; } cur = cur->_next; } return nullptr; } bool Erase(const K& key) { if (_tables.size() == 0) { return false; } size_t hashi = key % _tables.size(); Node* cur = _tables[hashi]; Node* prev = nullptr; while (cur) { if (cur._kv.first == key) { if (prev == nullptr) { _tables[hashi] = cur->_next; } else { prev->_next = cur->_next; } delete cur; return true; } else { prev = cur; cur = cur->_next; } } return false; } bool insert(const pair<K, V>& kv) { if (_tables.size() == 0) { return false; } //负载因子为1时扩容 if (_n == _tables.size()) { size_t newsize = _tables.size() == 0 ? 10 : _tables.size() * 2; //记得全部置为nullptr! vector<Node*> newtables(newsize, nullptr); for (auto& cur : _tables) { while (cur) { Node* next = cur->next; size_t hashi = cur._kv.first % newtables.size(); //头插到新表 cur->next = newtables[hashi]; newtables[hashi] = cur; cur = next; } } _tables.swap(newtables); } } private: vector<Node*> _tables; size_t _n = 0; }; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。