【C++】unordered_set和unordered_map

2024-04-16 21:04
文章标签 c++ set map unordered

本文主要是介绍【C++】unordered_set和unordered_map,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

底层哈希结构

namespace hash_bucket
{template<class T>struct HashData{T _data;struct HashData* next = nullptr;HashData(const T& data):_data(data){}};//仿函数:这里直接用开散列仿函数template <class K>struct HashFunc{size_t operator()(const K& key){return (size_t)key;}};template <>struct HashFunc<string>//特化{size_t operator()(const string& key){size_t res = 0;for (auto e : key){res *= 131;res += e;}return res;}};//迭代器//前置声明template<class K, class T, class Hash, class KeyOfT>class HashTable;template<class K, class T, class Hash, class KeyOfT>struct _HashTableIterator{typedef HashData<T> Node;typedef HashTable<K, T, Hash, KeyOfT> Ht;typedef _HashTableIterator<K, T, Hash, KeyOfT> Self;Node* _node;Ht* _pht;_HashTableIterator(Node* node,Ht* pht):_node(node),_pht(pht){}T& operator*(){return _node->_data;}T* operator->(){return &_node->_data;}Self& operator++(){if (_node->next){//当前桶_node = _node->next;}else{//下一个桶KeyOfT kot;Hash hash;size_t i = hash(kot(_node->_data)) % _pht->_size;for (++i; i < _pht->_tables.size(); i++){if (_pht->_tables[i]){_node = _pht->_tables[i];if(node)break;}}if (i == _pht->_tables.size()){_node = nullptr;}}return *this;}bool operator!=(Self& s)const{return s._node != _node;}bool operator==(Self& s)const{return !operator!=(s);}};template<class K, class T, class Hash, class KeyOfT>class HashTable{typedef HashData<T> Node;typedef _HashTableIterator<K, T, Hash, KeyOfT> iterator;public:iterator begin(){for (size_t i = 0; i < _tables.size(); i++){if (_tables[i] != nullptr)return iterator(_tables[i], this);}return end();}iterator end(){return iterator(nullptr, this);}public:HashTable():_size(0),_tables(10, nullptr){}~HashTable()//这里的析构函数得自己添加,否则只会析构哈希表,导致节点数据没有被释放{//这里的操作和底下的打印有点像for (size_t i = 0; i < _tables.size(); i++){Node* cur = _tables[i];while (cur){Node* next = cur->next;delete cur;cur = next;}_tables[i] = nullptr;}}bool Insert(const T& data){Hash hash;KeyOfT kot;if (Find(kot(data)))return false;//负载因子到 1 就扩容if (_size == _tables.size())//扩容{size_t newSize = _tables.size() * 2;vector<Node*> newTables(newSize, nullptr);size_t hashi = 0;for (size_t i = 0; i < _tables.size(); i++){Node* cur = _tables[i];while (cur){Node* next = cur->next;hashi = hash(kot(cur->_data)) % newTables.size();cur->next = newTables[hashi];newTables[hashi] = cur;cur = next;}_tables[i] = nullptr;}_tables.swap(newTables);}size_t hashi = hash(kot(data)) % _tables.size();//头插Node* old = _tables[hashi];_tables[hashi] = new Node(data);_tables[hashi]->next = old;_size++;return true;}Node* Find(const K& key){if (_size == 0)return nullptr;Hash hash;KeyOfT kot;size_t hashi = hash(key) % _tables.size();Node* cur = nullptr;for (size_t i = 0; i < _tables.size(); i++){cur = _tables[i];while (cur){if (kot(cur->_data) == key){return cur;}cur = cur->next;}}return nullptr;}void Print(){KeyOfT kot;for (size_t i = 0; i < _tables.size(); i++){Node* cur = _tables[i];while (cur){cout << "[" << kot(cur->_data) << ": " << kot(cur->_data) << "]-->";cur = cur->next;}}cout << endl;}bool Erase(const K& key){Hash hash;KeyOfT kot;size_t hashi = hash(key) % _tables.size();Node* cur = _tables[hashi];Node* prev = nullptr;while (cur){if (kot(cur->_data) == key){if (prev){prev->next = cur->next;}else{_tables[hashi] = cur->next;}delete cur;cur = nullptr;return true;}else{prev = cur;cur = cur->next;}}return false;}size_t size(){return _size;}private:size_t _size = 0;//有效数据个数vector<Node*> _tables;};
}

unordered_set

namespace hash_bucket
{template<class K, class Hash = HashFunc<K>>class unordered_set{struct SetKeyOfT{const K& operator()(const K& key){return key;}};private:HashTable<K, K,Hash,SetKeyOfT> _ht;public:typedef  typename HashTable<K, K, Hash, SetKeyOfT> ::iterator iterator;iterator begin(){return _ht.begin();}iterator end(){return _ht.end();}bool insert(const K& Node){return _ht.Insert(Node);}};void unorderedset_test1(){unordered_set<int> s;s.insert(2);s.insert(4);s.insert(9);s.insert(1);s.insert(2);s.insert(3);for (auto e : s){cout << e << " ";}}
}

unordered_map

namespace hash_bucket
{template<class K,class V, class Hash = HashFunc<K>>class unordered_map{struct MapKeyOfT{const K& operator()(const pair<K, V>& key){return key.first;}};private:HashTable<K, pair<K, V>, Hash, MapKeyOfT> _ht;public:typedef  typename HashTable<K, pair<K, V>, Hash, MapKeyOfT>::iterator iterator;iterator begin(){return _ht.begin();}iterator end(){return _ht.end();}bool insert(const pair<K, V>& Node){return _ht.Insert(Node);}};void unorderedmap_test1(){unordered_map<string, string> dict;dict.insert(make_pair("insert", "插入"));dict.insert(make_pair("sort" , "排序"));dict.insert(make_pair("delete", "删除"));dict.insert(make_pair("string", "字符串"));dict.insert(make_pair("iterator", "迭代器"));unordered_map<string, string>::iterator umit = dict.begin();//while (umit != dict.end())//{//	cout << umit->first << ":" << umit->second << endl;//	++umit;//}//cout << endl;}
}

此时编译:
在这里插入图片描述报错!
HashTable和其迭代器互相调用
从逻辑上讲,HashTable应该给迭代器开放权限,如下设置一个友元类即可
在这里插入图片描述
因为是模板故必须带参数。
经检测,以上代码有个小bug,可能会导致数据打印时无法跳出迭代器,形成死循环打印;
提示:错误点在该段代码中

		Self& operator++(){if (_node->next){//当前桶_node = _node->next;}else{//下一个桶KeyOfT kot;Hash hash;size_t i = hash(kot(_node->_data)) % _pht->_size;for (++i; i < _pht->_tables.size(); i++){if (_pht->_tables[i]){_node = _pht->_tables[i];if(node)break;}}if (i == _pht->_tables.size()){_node = nullptr;}}return *this;}

在这里插入图片描述
在这里我们是不是应该对哈希表的大小取模,而不是对现在的有效数据个数取模

size_t i = hash(kot(_node->_data)) % _pht->_tables.size();

完整代码

代码实现标准化,实现[ ]重载

#pragma once
#include "hash.h"
namespace hash_bucket
{template<class K, class Hash = HashFunc<K>>class unordered_set{struct SetKeyOfT{const K& operator()(const K& key){return key;}};private:HashTable<K, K,Hash,SetKeyOfT> _ht;public:typedef  typename HashTable<K, K, Hash, SetKeyOfT> ::iterator iterator;iterator begin(){return _ht.begin();}iterator end(){return _ht.end();}pair<iterator, bool> insert(const K& Node){return _ht.Insert(Node);}};void unorderedset_test1(){unordered_set<int> s;s.insert(2);s.insert(4);s.insert(9);s.insert(1);s.insert(2);s.insert(3);for (auto e : s){cout << e << " ";}}
}
#pragma once
#include "hash.h"
namespace hash_bucket
{template<class K,class V, class Hash = HashFunc<K>>class unordered_map{struct MapKeyOfT{const K& operator()(const pair<K, V>& key){return key.first;}};private:HashTable<K, pair<K, V>, Hash, MapKeyOfT> _ht;public:typedef  typename HashTable<K, pair<K, V>, Hash, MapKeyOfT>::iterator iterator;iterator begin(){return _ht.begin();}iterator end(){return _ht.end();}pair<iterator,bool> insert(const pair<K, V>& Node){return _ht.Insert(Node);}V& operator[](const K& key){pair<iterator, bool> ret = insert(make_pair(key, V()));return ret.first->second;}};void unorderedmap_test1(){unordered_map<string, string> dict;dict.insert(make_pair("insert", "插入"));dict.insert(make_pair("sort" , "排序"));dict.insert(make_pair("delete", "删除"));dict.insert(make_pair("string", "字符串"));dict.insert(make_pair("iterator", "迭代器"));unordered_map<string, string>::iterator umit = dict.begin();while (umit != dict.end()){cout << umit->first << ":" << umit->second << endl;++umit;}cout << endl;}void unorderedmap_test2(){string arr[] = { "梨子","苹果","猕猴桃","桃" ,"梨子","苹果", "猕猴桃","猕猴桃","猕猴桃","梨子","猕猴桃" };unordered_map<string, int> countMap;for (const auto& str : arr){countMap[str]++;}unordered_map<string, int>::iterator it = countMap.begin();while (it != countMap.end()){cout << (*it).first << ":" << (*it).second << endl;++it;}cout << endl << endl;for (auto e : countMap){cout << e.first << ":" << e.second << endl;}cout << endl;}
}
namespace hash_bucket
{template<class T>struct HashData{T _data;struct HashData* next = nullptr;HashData(const T& data):_data(data){}};//仿函数:这里直接用开散列仿函数template <class K>struct HashFunc{size_t operator()(const K& key){return (size_t)key;}};template <>struct HashFunc<string>//特化{size_t operator()(const string& key){size_t res = 0;for (auto e : key){res *= 131;res += e;}return res;}};//迭代器//前置声明template<class K, class T, class Hash, class KeyOfT>class HashTable;template<class K, class T, class Hash, class KeyOfT>struct _HashTableIterator{typedef HashData<T> Node;typedef HashTable<K, T, Hash, KeyOfT> Ht;typedef _HashTableIterator<K, T, Hash, KeyOfT> Self;Node* _node;Ht* _pht;_HashTableIterator(Node* node,Ht* pht):_node(node),_pht(pht){}T& operator*(){return _node->_data;}T* operator->(){return &_node->_data;}Self& operator++(){if (_node->next){//当前桶_node = _node->next;}else{//下一个桶KeyOfT kot;Hash hash;size_t i = hash(kot(_node->_data)) % _pht->_tables.size();for (++i; i < _pht->_tables.size(); i++){if (_pht->_tables[i]){_node = _pht->_tables[i];if (_node){break;}}}if (i == _pht->_tables.size()){_node = nullptr;}}return *this;}Self& operator++(int){Self tmp = this;if (_node->next){//当前桶_node = _node->next;}else{//下一个桶KeyOfT kot;Hash hash;size_t i = hash(kot(_node->_data)) % _pht->size();for (++i; i < _pht->_tables.size(); i++){if (_pht->_tables[i]){_node = _pht->_tables[i];break;}}if (i == _pht->_tables.size()){_node = nullptr;}}return tmp;}bool operator!=(const Self& s) const{return s._node != _node;}bool operator==(const Self& s) const{return s._node == _node;}};template<class K, class T, class Hash, class KeyOfT>class HashTable{template<class K, class T, class Hash, class KeyOfT>friend struct _HashTableIterator;typedef HashData<T> Node;public:typedef _HashTableIterator<K, T, Hash, KeyOfT> iterator;iterator begin(){for (size_t i = 0; i < _tables.size(); i++){if (_tables[i] != nullptr)return iterator(_tables[i], this);}return end();}iterator end(){return iterator(nullptr, this);}public:HashTable():_size(0),_tables(10, nullptr){}~HashTable()//这里的析构函数得自己添加,否则只会析构哈希表,导致节点数据没有被释放{//这里的操作和底下的打印有点像for (size_t i = 0; i < _tables.size(); i++){Node* cur = _tables[i];while (cur){Node* next = cur->next;delete cur;cur = next;}_tables[i] = nullptr;}}pair<iterator,bool> Insert(const T& data){Hash hash;KeyOfT kot;iterator ret = Find(kot(data));if (ret != end())return make_pair(ret, false); //负载因子到 1 就扩容if (_size == _tables.size())//扩容{size_t newSize = _tables.size() * 2;vector<Node*> newTables(newSize, nullptr);//这里为了减少调用,不像开散列那样采用复用insert的形式,而是直接将原表中的节点拿下来直接用//而且复用insert的时候会涉及空间的申请释放问题(申请新节点,将旧节点的值给新节点,然后释放新旧结点)size_t hashi = 0;//旧表数据移到新表//特别注意:一个一个数据移动,不可一串一串移动,那样的话会造成映射位置错误,最后使其数据不能被正常找到for (size_t i = 0; i < _tables.size(); i++){Node* cur = _tables[i];while (cur){Node* next = cur->next;hashi = hash(kot(cur->_data)) % newTables.size();cur->next = newTables[hashi];newTables[hashi] = cur;cur = next;}_tables[i] = nullptr;}_tables.swap(newTables);}size_t hashi = hash(kot(data)) % _tables.size();//头插Node* old = _tables[hashi];_tables[hashi] = new Node(data);_tables[hashi]->next = old;_size++;return make_pair(iterator(_tables[hashi], this), true);}iterator Find(const K& key){if (_size == 0)return iterator(nullptr, this);Hash hash;KeyOfT kot;size_t hashi = hash(key) % _tables.size();Node* cur = nullptr;for (size_t i = 0; i < _tables.size(); i++){cur = _tables[i];while (cur){if (kot(cur->_data) == key){return iterator(cur, this);}cur = cur->next;}}return end();}void Print(){KeyOfT kot;for (size_t i = 0; i < _tables.size(); i++){Node* cur = _tables[i];while (cur){cout << "[" << kot(cur->_data) << ": " << kot(cur->_data) << "]-->";cur = cur->next;}}cout << endl;}bool Erase(const K& key){Hash hash;KeyOfT kot;size_t hashi = hash(key) % _tables.size();Node* cur = _tables[hashi];Node* prev = nullptr;while (cur){if (kot(cur->_data) == key){if (prev){prev->next = cur->next;}else{_tables[hashi] = cur->next;}delete cur;cur = nullptr;return true;}else{prev = cur;cur = cur->next;}}return false;}size_t size(){return _size;}private:size_t _size = 0;//有效数据个数vector<Node*> _tables;};
}

这篇关于【C++】unordered_set和unordered_map的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/909893

相关文章

从入门到精通C++11 <chrono> 库特性

《从入门到精通C++11<chrono>库特性》chrono库是C++11中一个非常强大和实用的库,它为时间处理提供了丰富的功能和类型安全的接口,通过本文的介绍,我们了解了chrono库的基本概念... 目录一、引言1.1 为什么需要<chrono>库1.2<chrono>库的基本概念二、时间段(Durat

C++20管道运算符的实现示例

《C++20管道运算符的实现示例》本文简要介绍C++20管道运算符的使用与实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录标准库的管道运算符使用自己实现类似的管道运算符我们不打算介绍太多,因为它实际属于c++20最为重要的

Visual Studio 2022 编译C++20代码的图文步骤

《VisualStudio2022编译C++20代码的图文步骤》在VisualStudio中启用C++20import功能,需设置语言标准为ISOC++20,开启扫描源查找模块依赖及实验性标... 默认创建Visual Studio桌面控制台项目代码包含C++20的import方法。右键项目的属性:

c++中的set容器介绍及操作大全

《c++中的set容器介绍及操作大全》:本文主要介绍c++中的set容器介绍及操作大全,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录​​一、核心特性​​️ ​​二、基本操作​​​​1. 初始化与赋值​​​​2. 增删查操作​​​​3. 遍历方

解析C++11 static_assert及与Boost库的关联从入门到精通

《解析C++11static_assert及与Boost库的关联从入门到精通》static_assert是C++中强大的编译时验证工具,它能够在编译阶段拦截不符合预期的类型或值,增强代码的健壮性,通... 目录一、背景知识:传统断言方法的局限性1.1 assert宏1.2 #error指令1.3 第三方解决

C++11委托构造函数和继承构造函数的实现

《C++11委托构造函数和继承构造函数的实现》C++引入了委托构造函数和继承构造函数这两个重要的特性,本文主要介绍了C++11委托构造函数和继承构造函数的实现,具有一定的参考价值,感兴趣的可以了解一下... 目录引言一、委托构造函数1.1 委托构造函数的定义与作用1.2 委托构造函数的语法1.3 委托构造函

C++11作用域枚举(Scoped Enums)的实现示例

《C++11作用域枚举(ScopedEnums)的实现示例》枚举类型是一种非常实用的工具,C++11标准引入了作用域枚举,也称为强类型枚举,本文主要介绍了C++11作用域枚举(ScopedEnums... 目录一、引言二、传统枚举类型的局限性2.1 命名空间污染2.2 整型提升问题2.3 类型转换问题三、C

C++链表的虚拟头节点实现细节及注意事项

《C++链表的虚拟头节点实现细节及注意事项》虚拟头节点是链表操作中极为实用的设计技巧,它通过在链表真实头部前添加一个特殊节点,有效简化边界条件处理,:本文主要介绍C++链表的虚拟头节点实现细节及注... 目录C++链表虚拟头节点(Dummy Head)一、虚拟头节点的本质与核心作用1. 定义2. 核心价值二

C++ 检测文件大小和文件传输的方法示例详解

《C++检测文件大小和文件传输的方法示例详解》文章介绍了在C/C++中获取文件大小的三种方法,推荐使用stat()函数,并详细说明了如何设计一次性发送压缩包的结构体及传输流程,包含CRC校验和自动解... 目录检测文件的大小✅ 方法一:使用 stat() 函数(推荐)✅ 用法示例:✅ 方法二:使用 fsee

shell中set -u、set -x、set -e的使用

《shell中set-u、set-x、set-e的使用》本文主要介绍了shell中set-u、set-x、set-e的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参... 目录✅ 1. set -u:防止使用未定义变量 作用: 示例:❌ 报错示例输出:✅ 推荐使用场景:✅ 2. se