如何将这个C++哈希表转换为动态扩展和收缩,而不是使用硬设置的最大值

How can I convert this C++ hash table to dynamically expand and shrink instead of having a hard-set max value?

本文关键字:最大值 设置 C++ 哈希表 扩展 动态 转换      更新时间:2023-10-16

我在网上找到了一个哈希表实现。它的工作原理是存储值的固定限制为200。不,如果我需要更多,我不想只是增加硬性限制。相反,有没有一种方法可以使它动态扩展以容纳更多的值?

#include<iostream>
#include<cstdlib>
#include<string>
#include<cstdio>
using namespace std;
class HashTableEntry {
public:
int k;
int v;
HashTableEntry(int k, int v) {
this->k= k;
this->v = v;
}
};
class HashMapTable {
private:
HashTableEntry **t;
unsigned int t_s;
public:
HashMapTable() {
t = new HashTableEntry * [t_s];
t_s = 200;
for (int i = 0; i< t_s; i++) {
t[i] = NULL;
}
}
int HashFunc(int k) {
return k % t_s;
}
void Insert(int k, int v) {
int h = HashFunc(k);
while (t[h] != NULL && t[h]->k != k) {
h = HashFunc(h + 1);
}
if (t[h] != NULL)
delete t[h];
t[h] = new HashTableEntry(k, v);
}
int SearchKey(int k) {
int h = HashFunc(k);
while (t[h] != NULL && t[h]->k != k) {
h = HashFunc(h + 1);
}
if (t[h] == NULL)
return -1;
else
return t[h]->v;
}
void Remove(int k) {
int h = HashFunc(k);
while (t[h] != NULL) {
if (t[h]->k == k)
break;
h = HashFunc(h + 1);
}
if (t[h] == NULL) {
cout<<"No Element found at key "<<k<<endl;
return;
} else {
delete t[h];
}
cout<<"Element Deleted"<<endl;
}
~HashMapTable() {
for (int i = 0; i < t_s; i++) {
if (t[i] != NULL)
delete t[i];
delete[] t;
}
}
};

问题是,如果我使用realloc或其他东西并增加和减少t_s,它可能会更改存储值的键,并破坏哈希表。另一个问题是,当它没有存储任何项时,t_s将为0,而在hashFunc中,0的余数是未定义的。我该如何处理这些问题?我该如何在C++中创建一个动态递增和收缩的哈希表?

通常情况下;批处理计算";(没有任何实时灵敏度(只会点击并创建一个更大尺寸的副本,然后将其交换。

有一些方法可以增量增长哈希表,这样在增长的同时仍然可以访问O(1(,但隐藏在O(1"中的常量对于所有访问都会变大,而且很难正确处理。

在保留O(1(访问的同时具有增量增长的不同建议是具有"0";堆叠";哈希表-从一个200个条目的哈希表开始,然后当它达到填充极限(0.7或0.8满,无论你选择什么(时,在堆栈上推送一个400个条目的hash表,并在其中放入新条目。每次堆栈顶部满了,就在其上推送另一个空的双倍大小的哈希表。只在堆栈顶部添加条目。但是,在确定缺少项之前,必须在访问时搜索所有堆栈元素(每个哈希表(。所以你的O(1(访问增加了——但这是一个更简单的正确方案。