HashTable二次探测

先来了解一下哈希表的二次探测的原理
当前容量为:10
定义两个size_t 类型的变量 index,i = 0;
index = 89 % 10 = 9;查看下标为9的位置为空,所以89放在下标为9的位置;
index = 18 % 10 = 8;查看下标为8的位置为空,所以18放在下标为8的位置;
index = 49 % 10 = 9;查看下标为9的位置不为空,i++;index = index + i * i ;如果index大于当前的容量,则index=index-容量,再查看index的位置是否为空,当前index=0;将49放到下标为0的位置;i = 0;
index = 58 % 10 = 8;查看下标为8的位置不为空,i++;index = index + i * i ;如果index大于当前容量,则index=index-容量,再查看index的位置是否为空,当前index=9,不为空,index要先被置为8;i++;index = index + i * i;如果index大于当前的容量,则index=index-容量,再查看index的位置是否为空,当前index = 2 ;将58放到下标为2的位置;i = 0;
数字9和上面的同理,不再赘述。

下面来看看哈希表的增删查
#include <iostream>
using namespace std;
#include <string>

enum State
{
	EMPTY,
	EXIST,
	DELETE,
};

template <class K,class V>
struct HashTableNode
{
	K _key;
	V _value;
};

template <class K>
struct __HashFunc
{
	size_t operator()(const K& key)
	{
		return key;
	}
};

template<>
struct __HashFunc<string>
{
	size_t operator()(const string& key)
	{
		size_t value = 0;
		for (size_t i = 0; i < key.size(); ++i)
		{
			value += key[i];
		}
		return value;
	}
};

template<class K, class V, class HashFunc = __HashFunc<K>>
class HashTable
{
	typedef HashTableNode<K, V> Node;
public:
	HashTable(size_t capacity = 10)
		:_tables(new Node[capacity])
		, _states(new State[capacity])
		, _size(0)
		, _capacity(capacity)
	{
		for (size_t i = 0; i < _capacity; ++i)
		{
			_states[i] = EMPTY;
		}
	
	}
	bool Insert(const K& key, const V& value)
	{
		_CheckCapacity();
		size_t index = _HashFunc(key);
		size_t Cindex = index;
		int i = 0;
		while (_states[index] == EXIST)
		{
			if (index >= _capacity)
			{
				index = index - _capacity;
			}
			if (_tables[index]._key == key)
			{
				return false;
			}
			i++;
			index = Cindex;
			index = index + i*i;

		}
		_tables[index]._key = key;
		_tables[index]._value = value;
		_states[index] = EXIST;
		++_size;
		return true;
	}

	void Delete(const K& key)
	{
		Node* ret = Find(key);
		size_t index = ret - _tables;
		_states[index] = DELETE;
		_size--;
	}

	Node*  Find(const K& key)
	{
		size_t index = _HashFunc(key);
		const size_t Cindex = index;
		size_t i = 0;
		while (_states[index] != EMPTY)
		{
			if (index > _capacity)
			{
				index = index - _capacity;
			}
			if (_tables[index]._key == key)
			{
				if (_states[index] == DELETE)
					return NULL;
				return _tables+index;
			}
			i++;
			index = Cindex;
			index = index + i*i;
		}
		return NULL;
	}
	size_t _HashFunc(const K& key)
	{
		__HashFunc<K> hashFunc;
		size_t num = hashFunc(key) % _capacity;
		return num;
		//return __HashFunc(key) % _capacity;
	}
	void Print()
	{
		size_t index = 0;
		while (index < _capacity)
		{
			if (_states[index]==EXIST)
			cout << "["<<index<<"]" << ":" << "key:" << _tables[index]._key << "    value:" << _tables[index]._value << endl;
			index++;

		}
		cout << endl;
	}


protected:
	void _CheckCapacity()
	{
		if (_size * 10 / _capacity >= 7)
		{
			HashTable<K, V> tmp(2 * _capacity);
			for(size_t i = 0; i < _capacity; ++i)
			{
				if (_states[i] == EXIST)
				{
					tmp.Insert(_tables[i]._key,_tables[i]._value);
				}
			}
			this->Swap(tmp);
		}

	}
	void Swap(const HashTable<K, V>& ht)
	{
		swap(_capacity, (size_t)ht._capacity);
		swap(_size, (size_t)ht._size);
		swap(_tables, (Node*)ht._tables);
		swap(_states, (State*)ht._states);
	}
protected:
	Node* _tables;
	State* _states;
	size_t _size;
	size_t _capacity;
	
};

void TestDict()
{
	HashTable<string, string> dict;
	dict.Insert("dict", "字典");
	dict.Insert("hash", "哈希");
	dict.Insert("function", "函数");
	dict.Insert("abcd", "函数");
	dict.Insert("bcda", "函数");

	dict.Print();

	dict.Delete("bcda");
	dict.Print();

	HashTableNode<string, string>* ret = dict.Find("hash");
	if (ret)
	{
		cout << "hash的中文:" << ret->_value << endl;
	}
	else
	{
		cout << "找不到" << endl;
	}

	HashTable<int, int> h;
	h.Insert(4, 6);
	h.Print();
	HashTableNode<int, int>* ret1 = h.Find(4);
	if (ret1)
	{
		cout << "4:" << ret1->_value << endl;
	}
	else
	{
		cout << "找不到" << endl;
	}
}

int main()
{
	TestDict();
	system("pause");
	return 0;
}

在哈希表中的元素,我用枚举类型定义了三种状态:EMPTY,DELETE,EXIST;

值得注意的是有了_Checkcapacity(),哈希表是永远不会满的;
在_Checkcapacity()函数中_size * 10 / _capacity >= 7 来作为判断条件,是因为有一个散列表的载荷银子 α = 填入表中元素的个数 / 散列表的长度; α 越过0.8,则说明哈希冲突多,CPU的命中率低。所以我将 α 的值控制在 0.7以下,提高效率。

在hash表中有一种类型是string ,要用到函数模板的特化。
dict是一个英汉字典的模拟。




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++语言中的二次探测散列法是一种常见的散列表实现方法,用于解决哈希冲突问题。其基本思想是,当哈希函数计算出的位置已经被占用时,按照一定的规则在散列表中查找下一个空闲位置,直到找到为止。 具体实现过程如下: 1. 对于给定的关键字,通过哈希函数计算出它在散列表中的位置。 2. 如果该位置已经被占用,则按照二次探测法的规则,在散列表中查找下一个空闲位置。具体规则为,从当前位置开始,依次查找 $(1^2, 2^2, 3^2, \ldots)$ 个位置,直到找到一个空闲位置为止。 3. 如果散列表已经满了,则无法插入新的关键字。 4. 在查找时,如果找到了与待查找关键字相等的关键字,则说明该关键字已经存在于散列表中。 下面是二次探测散列法的C++代码实现: ```cpp const int MAX_SIZE = 10007; // 哈希表中的每个元素结构体 struct HashNode { int key; // 关键字 int value; // 值 }; // 哈希表类 class HashTable { public: HashTable(); ~HashTable(); void Insert(int key, int value); void Remove(int key); int Find(int key); private: HashNode* data; // 哈希表数据 int size; // 哈希表大小 int count; // 哈希表中元素个数 int HashFunc(int key); // 哈希函数 int GetNextPos(int pos, int i); // 获取下一个空闲位置 }; HashTable::HashTable() { size = MAX_SIZE; count = 0; data = new HashNode[size]; } HashTable::~HashTable() { delete[] data; } void HashTable::Insert(int key, int value) { int pos = HashFunc(key); int i = 0; while (data[pos].key != -1 && i < size) { pos = GetNextPos(pos, i); i++; } if (i >= size) { cout << "HashTable is full." << endl; return; } data[pos].key = key; data[pos].value = value; count++; } void HashTable::Remove(int key) { int pos = HashFunc(key); int i = 0; while (data[pos].key != key && i < size) { pos = GetNextPos(pos, i); i++; } if (i >= size) { cout << "Key not found." << endl; return; } data[pos].key = -1; data[pos].value = -1; count--; } int HashTable::Find(int key) { int pos = HashFunc(key); int i = 0; while (data[pos].key != key && i < size) { pos = GetNextPos(pos, i); i++; } if (i >= size) { cout << "Key not found." << endl; return -1; } return data[pos].value; } int HashTable::HashFunc(int key) { return key % size; } int HashTable::GetNextPos(int pos, int i) { return (pos + i * i) % size; } ``` 在上面的代码中,`HashTable` 类封装了二次探测散列法的实现细节,提供了插入、删除和查找操作。其中,`data` 数组存储了哈希表中的元素,`size` 表示哈希表的大小,`count` 表示哈希表中元素的个数。`HashFunc` 函数实现了哈希函数,`GetNextPos` 函数实现了获取下一个空闲位置的规则。在插入、删除和查找操作中,都需要通过哈希函数计算出待操作关键字在哈希表中的位置,然后按照二次探测法的规则查找下一个空闲位置或者待操作关键字所在的位置。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值