用C++实现哈希表的大小调整

Implementing resize of a hash table in C++

本文关键字:调整 哈希表 C++ 实现      更新时间:2024-03-29

我在c++中实现调整大小或扩展容量函数时遇到问题。这是我的调整大小(expandCapacity(功能:

template <typename K, typename V> void HashTable<K, V>::expandCapacity() {
LinearDictionary<K,V>* temp = this->hashTable;
this->capacity *= 2;
this->hashTable = new LinearDictionary<K,V>[this->capacity];
for(int i = 0; i < capacity; i++){
vector<pair<K,V>> items = temp[i].getItems();
for(int j = 0;j < temp[i].getSize(); i++){
K key = items[j].first;
V value = items[j].second;
int bucket = hash(key, capacity);
this->hashTable[bucket].insert(key, value);
}
}
delete temp;
}

这是我的插入函数:

template <typename K, typename V> void HashTable<K, V>::insert(K key, V value) {
int bucket = hash(key, capacity);
if(this->hashTable[bucket].contains(key)){
throw runtime_error("This key already exists");
}
this->hashTable[bucket].insert(key,value);
size+=1;
float loadFactor = (float)(size)/(float)(capacity);
if(loadFactor >= maxLoadFactor){
this->expandCapacity();
}
}

模板K表示键,V表示值。哈希表被实现为一个指向线性字典数组的指针(我自己实现的一个类本质上是一个键值对列表,它对字典有一些额外的有用功能(。但这似乎并没有扩大产能。相反,我不断得到一个错误"密钥已经存在"——这是我的教授实现的运行时错误。

您的i循环执行了太多迭代。当它正在访问的temp数据仅具有旧容量元素时,它基于新容量进行循环。