【发布时间】:2020-04-23 01:36:33
【问题描述】:
我在 C++ 中实现调整大小或扩展容量功能时遇到问题。这是我的 resize(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 代表值。哈希表被实现为一个指向线性字典数组的指针(我自己实现的一个类,它本质上是一个键值对列表,对字典有一些额外的有用功能)。但这似乎并没有扩大容量。相反,我不断收到错误“密钥已存在” - 这是我的教授实施的运行时错误。
【问题讨论】:
-
顺便说一句,实现扩展操作的一个相对简单的方法是首先实现一个swap_contents(HashTable & rhs)方法,它只是交换(this)和(rhs)的成员变量。一旦你实现了它,你可以简单地通过声明一个具有更大数组大小的临时第二个 HashTable 对象来实现 expandCapacity(),调用 temp=*this;然后调用 swap_contents(temp)
标签: c++ hash hashmap hashtable