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;};}

相关内容

热门资讯

宣布了!国内航线燃油附加费上涨... 继国际航线燃油附加费全面上调后,4月5日国内航线燃油附加费将上涨5倍。 4月1日,厦门航空、中国联合...
深天马A:将在穿戴、IT等终端... 6月6日消息,天马微电子(深天马A,000050.SZ)OLED研发中心产品开发部负责人杨康在媒体沟...
国内期货夜盘收盘涨跌不一,沥青... 6月6日消息,国内期货夜盘收盘涨跌不一,沥青、短纤涨超1%,豆油、豆二、玻璃、豆粕、棉花、淀粉、低硫...
杰创智能:拟不超6亿元采购服务... 6月6日消息,杰创智能公告称,公司根据未来发展规划,拟采购服务器并用于为客户提供智算云服务,采购总金...
香港证监会向持牌法团发出指引,... 6月6日消息,因应近期骗徒透过仿冒诈骗流动文字讯息中的超连结发动攻击(通常称为短讯仿冒诈骗)的事故有...
下周476.91亿元市值限售股... 6月6日消息,Wind数据统计显示,下周(6月9日-6月13日)共有44家公司限售股陆续解禁,合计解...
标普500指数期货和纳斯达克1... 6月6日消息,标普500指数期货和纳斯达克100指数期货涨幅扩大至1%。(广角观察)
年内基金发行突破4200亿份,... 6月6日消息,今年公募基金发行市场呈现“量增质优”的双重突破。公募排排网数据显示,截至6月5日,以认...
伊万科维奇:中国男足出局自己会... 6月6日消息,中国男足5日晚在2026美加墨世界杯亚洲区预选赛18强赛第九轮比赛中以0:1不敌印度尼...
空中客车5月交付51架飞机,较... 6月6日消息,欧洲空中客车公司表示,5月份该公司共交付51架飞机,数量较去年同期下降4%;今年迄今为...