【发布时间】:2013-11-18 00:14:22
【问题描述】:
我正在尝试通过删除旧表并创建一个具有相同内容的新表来重新散列表。我创建了一个 reHash 函数,但是这个函数会导致内存泄漏,导致执行该函数时程序崩溃。我找不到我的错误。
void HashMap::reHash()
{
int OldCapacity = cap;
cap = cap * 2 + 1; //set new capacity
Node** newHashTable = new Node*[cap]; //create a temporary table to hold info
for (int i = 0; i < cap; i++)
{
newHashTable[i] = nullptr;
}
const Node* n;
//fill in the new temp table with old info
for (int i = 0; i < OldCapacity; ++i)
{
n = HashTable[i];
while (n != nullptr)
{
//initialize new node
Node* nod = new Node;
nod->key = n->key;
nod->value = n->value;
nod->next = nullptr;
Node*& bucket = newHashTable[default_hash_function(n->key)/cap];
nod->next = bucket;
bucket = nod;
n = n->next;
}
}
// delete the links
for (int i = 0; i < OldCapacity; ++i)
{
Node *curr = HashTable[i];
Node *next;
while (curr != nullptr)
{
next = curr->next;
delete curr;
curr = next;
}
}
HashTable = newHashTable;
}
【问题讨论】:
-
您可以随时查看
std::unordered_map::rehash()的实现以获取灵感。 cplusplus.com/reference/unordered_map/unordered_map/rehash