4、hash函数的代码实现

本文详细介绍了哈希表的实现方式,包括使用分离链接法解决哈希冲突的策略。通过具体的C++代码示例,展示了哈希表的构造、扩容、添加、删除等操作,并解释了如何维护哈希表的负载因子。
#ifndef HASHTABLE
#define HASHTABLE
#include<vector>
#include<map>
using namespace std;
template<class K,class V>
class  HashTable{

private:
	const  static  int  upperTol = 10;
	const  static  int lowerTol = 2;
	const  static  int initCapacity = 7;

	map<K, V> * hashtable;
	int  num_element;
	int M;

	int hash(K key){  //求出 hash值
		return (std::hash<K>()(key)% M);
	}

	void resize(int newM){  //进行扩容操作
		map<K, V> * newHashTable = new map<K, V>[newM]();
		for (int i = 0; i < newM; i++)
			newHashTable[i] = map<K, V>();
		int oldM = M;
		this->M = newM;
		for (int i = 0; i < oldM; i++){
			map<K, V> map2 = hashtable[i];
			for (auto p : map2)
				newHashTable[hash(p.first)][p.first] = p.second;
		}
		this->hashtable = newHashTable;
	}


	//
public:
   HashTable(int M){
		this->M = M;
		num_element = 0;
		hashtable = new map<K, V>[M]();
		for (int i = 0; i < M; i++)
			hashtable[i] = map<K,V>();
	}

   HashTable(){
	   new (this) HashTable(initCapacity);  //placement new 
   }

  int getSize(){
	  return num_element;
   }

  void add(K key, V value){  
	 // cout << hash(key) << endl;
	  if (hashtable[hash(key)].count(key) == 1)  //判断里面的键,是否存在
			 hashtable[hash(key)][key] = value;
	  else{
		  hashtable[hash(key)][key] = value;
		  num_element++;
		  if (num_element >= upperTol*M){
			  resize(2*M);
		  }
	  }
  }


    V remove(K key){
	  V ret = NULL;
	  //map<K, V>  map2 = hashtable[hash(key)];
	  if (hashtable[hash(key)].count(key) == 1){
		  ret = hashtable[hash(key)].erase(key);
		  num_element--;
		  if (num_element <= lowerTol*M &&M / 2>= initCapacity){
			  resize(M/2);
		  }
	  }
	  return ret;
  }


 void set(K key, V value){
	  if (hashtable[hash(key)].count(key) == 1){
		  hashtable[hash(key)][key] = value;
	  }
	  else{
		  cout << "不存在该键值" << endl;
	  }
  }

  bool contains(K key){
	  return hashtable[hash(key)].count(key) == 1;
  }

  V get(K key){
	  return hashtable[hash(key)][key];
  }


};

#endif;

我们咋样解决hash冲突,上面是用的是seperate chaining 来解决。

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值