C++:哈希结构(内含unordered_set和unordered_map实现)
创始人
2025-05-28 09:58:33
0

unordered系列关联式容器

在C++98中,STL提供了底层为红黑树结构的一系列关联式容器,在查询时效率可达到$log_2 N$,即最差情况下需要比较红黑树的高度次,当树中的节点非常多时,查询效率也不理想。最好 的查询是,进行很少的比较次数就能够将元素找到,因此在C++11中,STL又提供了4个 unordered系列的关联式容器,这四个容器与红黑树结构的关联式容器使用方式基本类似,只是 其底层结构不同,本文中只对unordered_map和unordered_set进行介绍。

unordered_map和unordered_set的文档介绍

1. unordered_map是存储键值对的关联式容器,其允许通过keys快速的索引到与 其对应的value。

2. 在unordered_map中,键值通常用于惟一地标识元素,而映射值是一个对象,其内容与此 键关联。键和映射值的类型可能不同。

3. 在内部,unordered_map没有对按照任何特定的顺序排序, 为了能在常数范围内 找到key所对应的value,unordered_map将相同哈希值的键值对放在相同的桶中。

4. unordered_map容器通过key访问单个元素要比map快,但它通常在遍历元素子集的范围迭 代方面效率较低。

5. unordered_maps实现了直接访问操作符(operator[]),它允许使用key作为参数直接访问 value。

6. 它的迭代器至少是前向迭代器。

详情可以参考文档:

https://cplusplus.com/reference/unordered_set/unordered_set/?kw=unordered_set

底层结构

unordered系列的关联式容器之所以效率比较高,是因为其底层使用了哈希结构。

哈希概念

顺序结构以及平衡树中,元素关键码与其存储位置之间没有对应的关系,因此在查找一个元素 时,必须要经过关键码的多次比较。顺序查找时间复杂度为O(N),平衡树中为树的高度,即 O($log_2 N$),搜索的效率取决于搜索过程中元素的比较次数。

理想的搜索方法:可以不经过任何比较,一次直接从表中得到要搜索的元素。 如果构造一种存储结构,通过某种函数(hashFunc)使元素的存储位置与它的关键码之间能够建立 一一映射的关系,那么在查找时通过该函数可以很快找到该元素。

当向该结构中:

插入元素

        根据待插入元素的关键码,以此函数计算出该元素的存储位置并按此位置进行存放

搜索元素

        对元素的关键码进行同样的计算,把求得的函数值当做元素的存储位置,在结构中按此位置 取元素比较,若关键码相等,则搜索成功

该方式即为哈希(散列)方法,哈希方法中使用的转换函数称为哈希(散列)函数,构造出来的结构称 为哈希表(Hash Table)(或者称散列表)

例如:数据集合{1,7,6,4,5,9};

哈希函数设置为:hash(key) = key % capacity;

capacity为存储元素底层空间总的大小。

常见哈希函数

1. 直接定址法--(常用)

取关键字的某个线性函数为散列地址:Hash(Key)= A*Key + B 优点:简单、均匀 缺点:需要事先知道关键字的分布情况 使用场景:适合查找比较小且连续的情况 面试题:字符串中第一个只出现一次字符

2. 除留余数法--(常用)

设散列表中允许的地址数为m,取一个不大于m,但最接近或者等于m的质数p作为除数, 按照哈希函数:Hash(key) = key% p(p<=m),将关键码转换成哈希地址

3. 平方取中法--(了解)

假设关键字为1234,对它平方就是1522756,抽取中间的3位227作为哈希地址; 再比如关键字为4321,对它平方就是18671041,抽取中间的3位671(或710)作为哈希地址 平方取中法比较适合:不知道关键字的分布,而位数又不是很大的情况

直接定址法,需要是整型,且范围需要高度集中,除留余数法正是为了突破直接定址法的局限才被提出来,但是也引入了新的问题——哈希冲突。

注意:哈希函数设计的越精妙,产生哈希冲突的可能性就越低,但是无法避免哈希冲突。

哈希冲突

解决哈希冲突两种常见的方法是:闭散列和开散列

1. 开放地址法(闭散列) ,节点中含状态, 不能满,插入时要计算负载因子

2. 哈希桶/拉链法(开散列) 

如果不是整型,映射地址需要引入仿函数。

闭散列最大的缺陷就是空间利用率比较低,这也是哈希的缺陷。

闭散列实现

#pragma once
#include
#include
#includeusing namespace std;template
struct HashFunc
{size_t  operator()(const K& k){return (size_t)k;}
};template<>
struct HashFunc
{size_t  operator()(const string& k){size_t ret = 0;for (const auto& e : k){ret *= 131;ret += e;}return ret;}
};namespace HashClose
{enum  state{EXIST,DELETE,EMPTY,};templatestruct HashNode{pair _kv;state _sta = EMPTY;};template>class HashTable{public:typedef HashNode  Node;HashTable():_table(10),_n(0){}Node* find(const K& k){Hash hf;size_t hashi = hf(k) % _table.size();while (EMPTY != _table[hashi]._sta){if (EXIST == _table[hashi]._sta && k == _table[hashi]._kv.first){return &_table[hashi];}++hashi;hashi %= _table.size();}return nullptr;}bool  insert(const pair& kv){if (find(kv.first)){return false;}if (1.0 * _n / _table.size() >= 0.7){HashTable newtable;newtable._table.resize(2 * _table.size());for(const auto& e : _table){newtable.insert(e._kv);}_table.swap(newtable._table);}Hash hf;size_t hashi = hf(kv.first) % _table.size();while (EMPTY != _table[hashi]._sta){++hashi;hashi %= _table.size();}_table[hashi]._sta = EXIST;_table[hashi]._kv = kv;++ _n;}bool erase(const K& key){Node* ret = find(key);if (ret){ret->_sta = DELETE;--_n;return true;}else{return false;}}private:vector> _table;size_t _n;};void testht1(){HashTable ht;int a[] = { 18, 8, 7, 27, 57, 3, 38, 18 };for (auto e : a){ht.insert(make_pair(e, e));}ht.insert(make_pair(17, 17));ht.insert(make_pair(5, 5));cout << ht.find(7) << endl;cout << ht.find(8) << endl;ht.erase(7);cout << ht.find(7) << endl;cout << ht.find(8) << endl;}void testht2(){string arr[] = { "苹果", "西瓜", "香蕉", "草莓", "苹果", "西瓜", "苹果", "苹果", "西瓜", "苹果", "香蕉", "苹果", "香蕉" };//HashTable countHT;HashTable countHT;for (auto& e : arr){HashNode* ret = countHT.find(e);if (ret){ret->_kv.second++;}else{countHT.insert(make_pair(e, 1));}}HashFunc hf;cout << hf("abc") << endl;cout << hf("bac") << endl;cout << hf("cba") << endl;cout << hf("aad") << endl;}}

开散列

        开散列法又叫链地址法(开链法),首先对关键码集合用散列函数计算散列地址,具有相同地 址的关键码归于同一子集合,每一个子集合称为一个桶,各个桶中的元素通过一个单链表链 接起来,各链表的头结点存储在哈希表中。

 从上图可以看出,开散列中每个桶中放的都是发生哈希冲突的元素。

由于是一个数组下挂哈希桶,需要delete释放节点,需要写析构函数。

插入时头插。

扩容时旧节点重复利用

删除时与头节点交换,头删(也可以遍历直接删)

扩容时可以使容量为素数,以减少冲突

极端场景下,如果一个桶冲突过多,下面可以挂一个红黑树

开散列实现

namespace Hashbucket
{templatestruct  HashNode{HashNode(const T& t):_date(t),_next(nullptr){}T _date;HashNode* _next;};templateclass HashTable;templatestruct HashIterator{typedef HashIterator Self;typedef HashIterator*, HashNode*> Iterator;HTPTR _ht;HNPTR _hn;HashIterator(HTPTR ht, HNPTR hn):_ht(ht),_hn(hn){}HashIterator(const Iterator& it):_ht(it._ht), _hn(it._hn){}Ref operator*(){return _hn->_date;}Ptr operator->(){return &(_hn->_date);}Self& operator++(){if (_hn->_next){_hn = _hn->_next;}else{KeyOfV kov;size_t hashi = Hash()(kov(_hn->_date)) % _ht->_table.size();while (++hashi < _ht->_table.size()){if (_ht->_table[hashi]){_hn = _ht->_table[hashi];return *this;}}_hn = nullptr;}return *this;}bool operator!=(const Self& it)const{return it._hn != _hn;}};templateclass HashTable{public:templatefriend struct HashIterator;typedef HashTable  Self;typedef HashNode  Node;typedef HashIterator  iterator;typedef HashIterator  const_iterator;//默认构造HashTable():_n(0){_table.resize(9, nullptr);}HashTable(const Self& ht):_n(0){_table.resize(9, nullptr);for (const auto& e : ht){insert(e);}}iterator begin(){for (int i = 0; i < _table.size(); ++i){if (_table[i]){return iterator(this, _table[i]);}}return iterator(this, nullptr);}iterator end(){return iterator(this, nullptr);}const_iterator begin()const{for (int i = 0; i < _table.size(); ++i){if (_table[i]){return const_iterator(this, _table[i]);}}return const_iterator(this, nullptr);}const_iterator end()const{return const_iterator(this, nullptr);}iterator find(const K& key){Hash hs;KeyOfV kot;size_t hashi = hs(key) % _table.size();Node* cur = _table[hashi];while (cur){if (key == kot(cur->_date)){return iterator(this, cur);}cur = cur->_next;}return end();}//找到下一个要扩容的尺寸inline unsigned long __stl_next_prime(unsigned long n){static const int __stl_num_primes = 28;static const unsigned long __stl_prime_list[__stl_num_primes] ={53, 97, 193, 389, 769,1543, 3079, 6151, 12289, 24593,49157, 98317, 196613, 393241, 786433,1572869, 3145739, 6291469, 12582917, 25165843,50331653, 100663319, 201326611, 402653189, 805306457,1610612741, 3221225473, 4294967291};for (int i = 0; i < __stl_num_primes; ++i){if (__stl_prime_list[i] > n){return __stl_prime_list[i];}}return __stl_prime_list[__stl_num_primes - 1];}pair insert(const V& v){KeyOfV kot;//已经存在,不需要插入iterator it = find(kot(v));if (end() != it){return make_pair(it, false);}Hash hs;//负载因子超过1 ->  扩容if(_n == _table.size()){vector newtable;newtable.resize(__stl_next_prime(_table.size()), nullptr);for (int i = 0; i < _table.size(); ++i){Node* cur = _table[i];_table[i] = nullptr;Node* pre = nullptr;while (cur){size_t hashi = hs(kot(cur->_date)) % newtable.size();pre = cur;cur = cur->_next;pre-> _next = newtable[hashi];newtable[hashi] = pre;}}newtable.swap(_table);}//插入新节点size_t hashi = hs(kot(v)) % _table.size();Node* newnode = new Node(v);newnode->_next = _table[hashi];_table[hashi] = newnode;++_n;return make_pair(iterator(this, newnode), true);}private:vector  _table;size_t  _n;};}

unordered_set和unordered_map

#pragma once
#include"hash.h"namespace szg
{template>class unordered_set{public:struct setKeyOfV{const K& operator()(const K& k){return k;}};typedef typename Hashbucket::HashTable, setKeyOfV>::const_iterator iterator;typedef typename Hashbucket::HashTable, setKeyOfV>::const_iterator const_iterator;iterator begin(){return _ht.begin();}iterator end(){return _ht.end();}pair insert(const K& key){return _ht.insert(key);}private:Hashbucket::HashTable, setKeyOfV> _ht;};}
#pragma once
#include"hash.h"
namespace szg
{template>class unordered_map{public:struct mapKeyOfV{const K& operator()(const pair& v){return v.first;}};typedef typename Hashbucket::HashTable, HashFunc, mapKeyOfV>::iterator  iterator;typedef typename Hashbucket::HashTable, HashFunc, mapKeyOfV>::const_iterator  const_iterator;iterator begin(){return _ht.begin();}iterator end(){return _ht.end();}pair insert(const K& key){return _ht.insert(key);}V& operator[](const K& key){pair ret = _ht.insert(make_pair(key, V()));return ret.first->second;}private:Hashbucket::HashTable, HashFunc, mapKeyOfV> _ht;};}

相关内容

热门资讯

无人驾驶赛道“波涛汹涌”,小马... 中国新能源汽车的竞争焦点,正从电动化转向智能化。12月15日,工业和信息化部正式公布我国首批L3级有...
2026年AI投资究竟有没有泡... 中经记者 谭志娟 北京报道2025年以来,A股市场科技板块表现亮眼,人工智能相关股票涨势尤为突出,不...
2025汽油发动机1-11月销... 汽油发动机,没落了吗?新能源汽车时代的到来,汽油发动机行业是首当其冲!不过,进入2025年我国的多缸...
贾国龙当学老乡鸡 贾国龙道歉了,180度的那种,还搭配了不少媒体夸他“真诚”的软文。“连续40天靠吃安眠药入睡……”几...
探索居家养老服务,富德生命人寿... 在当前我国人口老龄化持续深化的背景下,养老金融服务的重要性日益凸显。根据国家统计局数据,截至2024...
年终盘点|2025年:“中国新... 中国商报(记者 马嘉)2025年,中国创新药产业的叙事基调发生了改变。衡量行业价值的标尺,已从实验室...
伏达半导体启动北交所上市辅导,... 红星资本局12月29日消息,中国证监会网上办事服务平台信息显示,安徽证监局受理了伏达半导体(合肥)股...
突发!利空来袭,全线杀跌! 一边是如火的大宗,一边是如冰的国债!今日午后,国债期货持续走弱,30年期主力合约盘中跌1.10%,1...
舰机多向抵近台岛!东部战区开展... 东部战区新闻发言人施毅陆军大校表示,12月29日开始,中国人民解放军东部战区组织陆军、海军、空军、火...
接不住梗的编辑不是好运营!到底... 来源 | 本文由微信公众号“文案圈”整理导读 如果不是亲眼看到我们很难想象:莫言, 这位把文字写进无...