指针的链接列表上的C++重排
我有一个功能齐全的hashMap类,除了一个rehash函数外,其他一切似乎都运行得很好,该函数用于在前一个hashMap的负载因子达到0.8时创建hashMap指针的链接列表上的C++重排,c++,for-loop,linked-list,hashmap,C++,For Loop,Linked List,Hashmap,我有一个功能齐全的hashMap类,除了一个rehash函数外,其他一切似乎都运行得很好,该函数用于在前一个hashMap的负载因子达到0.8时创建hashMap void HashMap::reHash() { logins = 0; numberOfPairs = 0; Node** newBucket = new Node* [(2 * lengthOfMap) + 1]; for(int i = 0; i < lengthOfMap; i++)
void HashMap::reHash()
{
logins = 0;
numberOfPairs = 0;
Node** newBucket = new Node* [(2 * lengthOfMap) + 1];
for(int i = 0; i < lengthOfMap; i++)
{
Node* oldHead = bucketList[i];
for(Node* temp = oldHead; temp != nullptr; temp = temp-> next)
{
std::string key = oldHead->key;
std::string value = oldHead->value;
unsigned int index = hash(key) % lengthOfMap;
if(newBucket[index] == nullptr)
{
std::cout << "HIT" << std::endl;
newBucket[i] = new Node;
newBucket[i]->key = key;
newBucket[i]->value = value;
newBucket[i]->next = nullptr;
numberOfPairs[index]++;
logins++;
}
else if (bucketList[index] != nullptr)
{
Node* temp = bucketList[index];
while(temp->next != nullptr)
{
temp = temp->next;
}
Node* n = new Node;
n->key = key;
n->value = value;
temp->next = n;
n->next = nullptr;
std::cout << "FAIL at index: " << index << std::endl;
//numberOfPairs[index]++;
logins++;
}
}
}
for(int i = 0; i < lengthOfMap; ++i)
{
if( bucketList[i] )
{
Node* first = bucketList[i];
while( first )
{
Node* temp = first->next;
delete first;
first = temp;
}
}
}
delete bucketList;
bucketList = newBucket;
lengthOfMap = (2 * lengthOfMap) + 1;
}
bucketList[]是我以前的数组,其中包含节点*,每个节点都从链表中的第一个链接开始。为了我自己的利益,我添加了两个std::cout,我似乎一次又一次地陷入索引为0时读取失败的永久循环中。我承认我不熟悉遍历链表的for循环,我认为这是我问题的根源,但我正在寻找任何有用的输入。
再次感谢。旁注:如果足够小心,您可以在不重新分配任何节点的情况下执行此操作。您可以将节点从一个存储桶列表移动到另一个存储桶列表。这有点乏味,但是性能优势,特别是对于昂贵的对象拷贝,是值得的。@WhozCraig你是如何这样移动节点的?实际上我刚刚回顾了整个算法,它是一团混乱,很抱歉残酷的事实,但这是事实。你没有为你的新模数使用正确的大小,你在插入一个新的列表头i应该是索引时使用了错误的索引,等等。不管怎样,你可能至少需要部分重写。如果你这样做了,你也可以通过所有新的重新分配来停止疯狂。如果我有时间,我会贴些东西。