HashTable.h
#pragma once
#include <functional>
template<typename Key,typename Value,typename Hash = hash<Key>>
class HashTable
{
private:
Key** key = nullptr;
Value** value = nullptr;
int kvcount = 0;
int size = 0;
public:
HashTable(int cap)
{
key = new Key*[cap];
value = new Value*[cap];
for (int i = 0; i < cap; ++i)
{
key[i] = nullptr;
value[i] = nullptr;
}
size = cap;
}
int Myhash(const Key& k)
{
return (Hash()(k) & 0x7fffffff) % size;
}
/******************************************
函数名称: resize
函数说明: 调整散列表大小
返回值: void
*******************************************/
void resize(int m)
{
HashTable<Key, Value, Hash> *ht = new HashTable(m);
for (int i = 0; i < size; ++i)
if (key[i] != nullptr)
{
ht->put(*key[i], *value[i]);
}
key = ht->key;
value = ht->value;
size = ht->size;
delete ht;
}
/******************************************
函数名称: put
函数说明: 存储key-value于散列表中
返回值: void
*******************************************/
void put(const Key& k, const Value& v)
{
if (kvcount >= size / 2)
resize(2 * size);
int index = Myhash(k);
for (index = Myhash(k); key[index] != nullptr; index = (index + 1) % size)
{
if (*(key[index]) == k)
{
*(value[index]) = v;
return;
}
}
key[index] = new Key(k);
value[index] = new Value(v);
++kvcount;
}
/******************************************
函数名称: get
函数说明: 得到key在散列表的value
返回值: value
*******************************************/
Value get(const Key& k)
{
for (int index = Myhash(k); key[index] != nullptr; index = (index + 1) % size)
{
if (*key[index] == k)
return *value[index];
}
throw std::out_of_range("can't get");
}
/******************************************
函数名称: exist
函数说明: 判断key是否存在于散列表
返回值: bool
*******************************************/
bool exist(const Key& k)
{
int index = Myhash(k);
for (; key[index] != nullptr; index = (index + 1) % size)
{
if (*key[index] == k)
return true;
}
return false;
}
/******************************************
函数名称: erase
函数说明: 删除key--value
返回值: void
*******************************************/
void erase(const Key& k)
{
if (!exist(k))
return;
int index = Myhash(k);
while (*key[index] != k)
index = (index + 1) % size;
key[index] = nullptr;
value[index] = nullptr;
index = (index + 1) % size;
while (key[index] != nullptr)
{
Key nk = *key[index];
Value nv = *value[index];
key[index] = nullptr;
value[index] = nullptr;
--kvcount;
put(nk, nv);
index = (index + 1) % size;
}
--kvcount;
if (kvcount > 0 && kvcount == size / 8)
resize(size / 2);
}
int kvsize()
{
return kvcount;
}
};
main.cpp
#include <iostream>
#include "HashTable.h"
using namespace std;
int main()
{
HashTable<string, int> ht(30);
string a[] = { "Marco","Tom","Jerry","Mary","Happy","Sad","Ugly","Handsome","Cola","Thanks" };
for (int i = 0; i < 10; ++i)
ht.put(a[i], i);
cout << boolalpha << ht.exist("Marco") << endl;
ht.erase("Marco");
ht.erase("Tom");
//ht.get("Marco");
cout << ht.exist("Marco") << endl;
cout << ht.kvsize();
system("pause");
return 0;
}
运行: