C++手动实现一个开链法HashMap

1.HashMap原理

参考我的博客:https://blog.youkuaiyun.com/Revendell/article/details/110009858

  • 开链法:STL的hashtable便是采用开链法解决冲突。这种做法是在每一个表格元素中维护一个list:散列函数为我们分配某一个list,然后我们在那个list身上执行元素的插入、搜寻、删除等操作。虽然针对list而进行的搜寻只能是一种线性操作,但如果list够短,速度还是够快。使用开链法,表格的负载系数将大于1(元素个数除以表格大小)。
  • 动态扩容:buckets聚合体以vector完成,以利动态扩充,vector<node*,Alloc> buckets。num_elements为hashtable中元素个数,bucket_count()返回bucket个数即buckets vector的大小。hashtable的计算元素位置赋予给了函数bkt_num(),通过它调用散列函数取得一个可以执行取模运算的值。开链法并不要求表格大小必须为质数,但STL仍然以质数来设计表格大小,并且先将28个质数计算好,逐渐呈现大约两倍的关系,以备随时访问,同时提供一个函数,用来查询在这28个质数之中最接近某数并大于某数的质数。

2.代码解析

  • 数据结构:这个实现选择使用向量和链表来处理可能出现的哈希冲突。std::vector<std::list<std::pair<K, V>>> table:底层容器是一个向量,其每个元素是一个链表,用于存储具有相同哈希值的键值对。
  • 哈希函数std::hash<K>()(key) 用于生成哈希值,这个哈希函数对许多内置类型都有定义,你也可以根据需要自定义。
  • 插入操作:在插入时,首先通过计算哈希值确定需要插入的链表。如果键已经存在,就更新其值,否则在链表尾部插入新的键值对。
  • 删除操作:删除时,找到对应的键,并将其从链表中移除。
  • 查找操作:查找时,通过哈希和链表搜索来快速找到键对应的值。如果找到了键,则返回关联的值。

3.代码实现

#include<iostream>
#include<vector>
#include<list>
#include<algorithm>
using namespace std;
template <typename K, typename V>
class HashMap {
public:
  HashMap(size_t size = 101) : table(size) {}
  bool insert(const K &key, const V &value) {
    const size_t pos = my_hash(key) % table.size();
    list<pair<K, V>> &chain = table[pos];
    for (typename list<pair<K, V>>::iterator iter = chain.begin(); iter != chain.end(); ++iter) {
      if (iter->first == key) {
        iter->second = value;
        return true;
      }
    }
    chain.push_back(pair<K, V>(key, value));
    return true;
  }
  bool erase(const K &key) {
    const size_t pos = my_hash(key) % table.size();
    list<pair<K, V>> &chain = table[pos];
    for (typename list<pair<K, V>>::iterator iter = chain.begin(); iter != chain.end(); ++iter) {
      if (iter->first == key) {
        chain.erase(iter);
        return true;
      }
    }
    return false;
  }

  bool search(const K &key, V &value) {
    const size_t pos = my_hash(key) % table.size();
    list<pair<K, V>> &chain = table[pos];
    for (typename list<pair<K, V>>::iterator iter = chain.begin(); iter != chain.end(); ++iter) {
      if (iter->first == key) {
        value = iter->second;
        return true;
      }
    }
    return false;
  }

private:
  vector<list<pair<K, V>>> table;
  size_t my_hash(const K &key) {
    return hash<K>()(key);
  }
};

int main()
{
  HashMap<std::string, int> map;
  if (map.insert("apple", 3)) {
    cout << "Apple insert success" << endl;
  }
  if (map.insert("banana", 2)) {
    cout << "Banana insert success" << endl;
  }
  if (map.insert("orange", 5)) {
    cout << "Orange insert success" << endl;
  }
  int value;
  if (map.search("apple", value)) {
    cout << "Apple search success: " << value << endl;
  } else {
    cout << "Apple search fail" << endl;
  }
  if (map.erase("banana")) {
    cout << "Banana erase success" << endl;
  }
  if (map.search("banana", value)) {
    cout << "Banana search success: " << value << endl;
  } else {
    cout << "Banana search fail" << endl;
  }
  return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值