哈希冲突 与 STL 里hashtable的实现 哈希桶vector<Node*> bucket + 链表实现,每次冲突更改对应bucket的链表头节点

📌 哈希冲突(Hash Collision)定义

哈希冲突(Hash Collision) 发生在 不同的键(Key)通过哈希函数映射到相同的哈希值(索引) 的情况。


📌 1. 为什么会发生哈希冲突?

哈希冲突是不可避免的,主要原因有:

  1. 有限的桶数量:哈希表的**桶(bucket)**数量通常比所有可能的键空间要小。
  2. 哈希函数的碰撞:哈希函数不能保证唯一性,不同的输入可能映射到相同的哈希值。
  3. 鸽巢原理(Pigeonhole Principle):如果有 N 个键,但只有 M 个桶(N > M),则必定存在 至少两个键映射到同一个桶

🚀 示例

假设哈希表有 5 个桶(索引 0 ~ 4),我们使用哈希函数:

hash(key) = key % 5

📌 哈希值计算

Key = 10  → hash(10) = 10 % 5 = 0
Key = 15  → hash(15) = 15 % 5 = 0 (冲突)

1015 发生哈希冲突,因为它们映射到同一个索引 0


📌 哈希冲突(Hash Collision)

哈希冲突 发生在 两个不同的键(Key)映射到同一个哈希值(Bucket 位置) 的情况。在 hashtable(哈希表)中,哈希冲突是 不可避免 的,因为哈希函数的值域(桶的数量)通常小于可能的键值域。


📌 1. 为什么会发生哈希冲突?

🚀 1.1 哈希函数的有限性

  • 哈希函数 hash(key) % bucket_count 计算出的哈希值 bucket_count 之内
  • 但可能的 键空间(key space)远远大于 bucket_count

📌 示例

hash("apple") % 10  → 3
hash("orange") % 10 → 3  (冲突)

🔹 “apple” 和 “orange” 的哈希值相同,导致哈希冲突!


📌 2. 解决哈希冲突的方法

哈希表常用的哈希冲突解决方案有两种:

  1. 链地址法(Chaining)
  2. 开放寻址法(Open Addressing)

📌 3. 链地址法(Chaining)

🔹 思路:

  • 每个哈希桶(Bucket)存储一个链表(linked list)
  • 当多个键值对映射到同一个桶时,使用链表存储多个元素

🚀 示例

哈希桶(bucket):
 ┌───────┬───────┬───────┬───────┬───────┐
 │  0    │  1    │  2    │  3    │  4    │  
 └───┬───┴───┬───┴───┬───┴───┬───┴───┬───┘
     ↓       ↓       ↓       ↓       ↓
  [Key1, Val1] → [Key5, Val5]   NULL   [Key2, Val2] → [Key6, Val6]

📌 代码实现

#include <iostream>
#include <vector>
#include <list>

class HashTable {
   
   
private:
    std::vector<std::list<int>> table;
    size_t bucket_count;

    size_t hash_function(int key) {
   
    return key % bucket_count; }

public:
    HashTable(size_t size) 
#pragma once #include <iostream> #include <utility> #include <assert.h> #include <vector> using namespace std; namespace bit { template<class K> struct HashFunc { size_t operator()(const K& key) { return (size_t)key; } }; // 为了实现简单,在哈希桶的迭代器类中需要用到hashBucket本身, template<class K, class V, class KeyOfValue, class Hash> class HashBucket; template<class T> class HashBucketNode; // 注意:因为哈希桶在底层是单链表结构,所以哈希桶的迭代器不需要--操作 template <class K, class V, class KeyOfValue, class Hash = HashFunc<K>> struct HBIterator { typedef HashBucket<K, V, KeyOfValue, Hash> HashBucket; typedef HashBucketNode<V>* PNode; typedef HBIterator<K, V, KeyOfValue, Hash> Self; HBIterator(PNode pNode = nullptr, HashBucket* pHt = nullptr) :_pNode(PNode) ,_pHt(pHt) {} HBIterator(const HBIterator<K, V, KeyOfValue, Hash>& it) { *_pHt = *(it._pHt); _pNode = it._pNode; } Self& operator++() { // 当前迭代器所指节点后还有节点时直接取其下一个节点 if (_pNode->_pNext) _pNode = _pNode->_pNext; else { // 找下一个不空的桶,返回该桶中第一个节点 size_t bucketNo = _pHt->HashFunc(KeyOfValue()(_pNode->_data)) + 1; for (; bucketNo < _pHt->BucketCount(); ++bucketNo) { _pNode = _pHt->_ht[bucketNo]; if (_pNode) break; } if (bucketNo == _pHt->BucketCount()) _pNode = nullptr; } return *this; } Self operator++(int) { Self temp = *this; ++(*this); return temp; } V& operator*() { KeyOfValue kot; return _pNode->_data; } V* operator->() { return &_pNode->_data; } bool operator==(const Self& it) const { return _pNode == it._pNode; } bool operator!=(const Self& it) const { return _pNode != it._pNode; } PNode _pNode; // 当前迭代器关联的节点 HashBucket* _pHt; // 哈希桶--主要是为了找下一个空桶时候方便 }; // unordered_map中存储的是pair<K, V>的键值对,K为key的类型,V为value的类型,HF哈希函数类型 // unordered_map在实现时,只需将hashbucket中的接口重新封装即可 template<class K, class V, class HF = DefHashF<K>> class unordered_map { typedef HashBucket<K, pair<K, V>, KeyOfValue, HF> HT; // 通过key获取value的操作 struct KeyOfValue { const K& operator()(const pair<K, V>& data) { return data.first; } }; public: typename typedef HT::Iterator iterator; public: unordered_map() : _ht() {} //////////////////////////////////////////////////// iterator begin() { return _ht.begin(); } iterator end() { return _ht.end(); } //////////////////////////////////////////////////////////// // capacity size_t size()const { return _ht.size(); } bool empty()const { return _ht.empty(); } /////////////////////////////////////////////////////////// // Acess V& operator[](const K& key) { pair<iterator, bool> ret = _ht.InsertUnique(pair<K, V>(key, V())); return ret.fisrt->second; } const V& operator[](const K& key)const; ////////////////////////////////////////////////////////// // lookup iterator find(const K& key) { return _ht.Find(key); } size_t count(const K& key) { return _ht.Count(key); } ///////////////////////////////////////////////// // modify pair<iterator, bool> insert(const pair<K, V>& valye) { return _ht.Insert(valye); } iterator erase(iterator position) { return _ht.Erase(position); } //////////////////////////////////////////////////////////// // bucket size_t bucket_count() { return _ht.BucketCount(); } size_t bucket_size(const K& key) { return _ht.BucketSize(key); } private: HT _ht; }; template<class T> struct HashBucketNode { T _data; HashBucketNode<T>* _next; HashBucketNode(const T& data) :_data(data) , _next(nullptr) {} }; template<class K, class T, class KeyOfT, class Hash> class HashBucket { typedef HashBucketNode<T> Node; typedef HashBucket<K, T, KeyOfT, Hash> Self; public: template<class K> struct HashFunc { size_t operator()(const K& key) { return (size_t)key; } }; unsigned long __stl_next_prime(unsigned long n) { // Note: assumes long is at least 32 bits. 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 }; const unsigned long* first = __stl_prime_list; const unsigned long* last = __stl_prime_list + __stl_num_primes; const unsigned long* pos = lower_bound(first, last, n); return pos == last ? *(last - 1) : *pos; } HashBucket() { _tables.resize(__stl_next_prime(_tables.size()), nullptr); } HashBucket(const Self& ht) { _tables = new Node(ht._tables.size(), nullptr); _n = ht._n; for (size_t i = 0; i < _tables.size(); i++) { Node* cur = ht._tables[i]; Node* prev = nullptr; while (cur) { Node* newnode = new Node(cur->_data); if (prev == nullptr) { _tables[i] = newnode; } else { prev->_next = newnode; } prev = cur; cur = cur->_next; } } } Self& operator=(const Self& ht) { _tables.resize(ht._tables.size(), nullptr); _n = ht._n; for (size_t i = 0; i < _tables.size(); i++) { Node* cur = ht._tables[i]; Node* prev = nullptr; while (cur) { Node* newnode = new Node(cur->_data); if (prev == nullptr) { _tables[i] = newnode; } else { prev->_next = newnode; } prev = cur; cur = cur->_next; } } } // 哈希桶的销毁 ~HashBucket() { for (auto& e : _tables) { Node* cur = e; Node* next = nullptr; while (cur) { next = cur->_next; delete cur; cur = next; } } } // 插入值为data的元素,如果data存在则不插入 bool Insert(const T& data) { KeyOfT kot; Hash hash; if (_n == _tables.size()) { HashTable<K, T, KeyOfT, Hash> newTable(__stl_next_prime(_n + 1), nullptr); for (auto& e : _tables) { Node* cur = e; size_t i = 0; while (cur) { Node* next = cur->_next; size_t hashi = hash(kot(cur->_data)) % newTable.size(); cur->_next = newTable[hashi]; newTable[hashi] = cur; cur = next; } _tables[i++] = nullptr; } _tables.swap(newTable); } size_t hashi = hash(kot(data)) % _tables.size(); Node* newnode = new Node(data); newnode->_next = _tables[hashi]; _tables[hashi] = newnode; _n++; return true; } // 在哈希桶中查找值为key的元素,存在返回true否则返回false bool Find(const K& key) { KeyOfT kot; Hash hash; size_t hashi = hash(key) % _tables.size(); Node* cur = _tables[hashi]; while (cur) { if (kot(cur->_data) == key) return true; cur = cur->_next; } return false; } // 哈希桶中删除key的元素,删除成功返回true,否则返回false bool Erase(const K& key) { KeyOfT kot; Hash hash; size_t hashi = hash(key) % _tables.size(); Node* prev = nullptr; Node* cur = _tables[hashi]; while (cur) { if (kot(cur->_data) == key) { if (prev == nullptr) { _tables[hashi] = cur->_next; delete cur; } else { prev->_next = cur->_next; delete cur; } --_n; return true; } prev = cur; } return false; } private: vector<Node*> _tables; // 指针数组 size_t _n = 0; // 表中存储数据个数 }; }
07-10
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值