【发布时间】:2012-04-15 17:31:37
【问题描述】:
我的代码中出现了一个非常奇怪的错误。这个作业是为我正在上的一门课准备的,基本上我们正在学习如何实现一个哈希表。我得到的错误是当我尝试重新散列到更大的尺寸时。这是给我问题的代码部分,我将更全面地解释问题所在。
if(htable->size>=htable->cap)
{
cout<<htable->cap<<endl;
HashTable tempht=*htable;
delete htable;
htable=new HashTable((tempht.cap * 2) + 1);
for (size_t i=0; i<tempht.cap; i++)
{
Node* n=tempht.table[i];
while (n!=NULL)
{
htable->add(n->item);
n=n->next;
}
}
if (htable->table[0]==NULL)
{
cout<<"HOORAY!"<<endl;
}
}
if (htable->table[0]==NULL)
{
cout<<"HOORAY!"<<endl;
}
else
{
cout<<htable->table[0]->item<<endl;
}
htable 是一个 HashTable 变量。在HashTable 类中,它包含一个数组Node*(节点只是我创建的包含字符串和指向链中下一项的指针的对象)。这部分代码只是试图重新散列到更大的表。我遇到的问题是,一旦我退出第一个 if 语句,我的表的第一个值不再等于 NULL(我正在运行的测试将一个没有任何内容的表重新散列到一个仍然没有任何内容但有容量更大)。当我运行代码时,第一个 htable->table[0]==NULL 通过,而第二个没有通过,尽管除了退出 if 语句之外没有任何更改(我的预期结果是 table[0] 应该为 NULL)。我最好的猜测是这是某种范围界定错误,但老实说,我看不出问题出在哪里。任何帮助将不胜感激。
编辑:澄清一下,初始哈希表的容量为 0(这是项目要求之一)。因此,当我尝试向表中添加项目时,会执行此 if 语句(因为大小为 0 且上限为 0,我们必须保持负载因子为 1)。我可以确认,一旦表格到达第一次和第二次“万岁”检查,htable->cap(这是阵列的总容量)为 1,这应该是。唯一弄乱的是存储桶 0(在这种情况下是唯一的存储桶)。无论出于何种原因,它在退出 if 语句之前为空,但之后不为空。
我正在发布我的整个HashTable 课程,如果你发现了什么,请告诉我。
#pragma once
#include <iostream>
#include <string>
#include <fstream>
#include "Node.h"
using namespace std;
class HashTable
{
public:
Node** table;
int size;
int cap;
HashTable (int c)
{
size=0;
cap=c;
table = new Node*[cap];
if (cap>0)
{
for (size_t i=0; i<cap; ++i)
{
table[i]=NULL;
}
}
}
~HashTable()
{
delete table;
}
size_t hash(string thing)
{
size_t total=0;
int asci;
char c;
size_t index;
for (size_t i=0; i<thing.length(); i++)
{
total=total*31;
c=thing[i];
asci=int(c);
total=asci+total;
}
index=total%cap;
cout<<"index"<<index<<endl;
system("pause");
return index;
}
void add(string thing)
{
size_t index;
index=hash(thing);
cout<<"index "<<index<<endl;
system("pause");
Node* temp=table[index];
if (temp==NULL)
{
cout<<"Here"<<endl;
system("pause");
}
else
{
cout<<"Here2"<<endl;
system("pause");
cout<<"temp"<<temp->item<<endl;
system("pause");
}
Node* n = new Node(thing);
cout<<"n"<<n->item<<endl;
system("pause");
if (temp==NULL)
{
table[index]=n;
}
else
{
while (temp->next!=NULL)
{
temp=temp->next;
}
temp->next=n;
}
size++;
}
Node* find(string search)
{
Node* n= NULL;
size_t index;
if(cap!=0)
{
index=hash(search);
Node* temp=table[index];
while (temp!=NULL)
{
if (temp->item==search)
{
n=temp;
return n;
}
}
}
return n;
}
void remove (string thing)
{
if (find(thing)==NULL)
{
return;
}
else
{
size_t index;
index=hash(thing);
Node* temp=table[index];
if (temp->item==thing)
{
table[index]=temp->next;
delete temp;
}
while (temp->next!=NULL)
{
if (temp->next->item==thing)
{
Node* temp2=temp->next;
temp->next=temp->next->next;
delete temp2;
break;
}
}
}
size--;
}
void print(ofstream &ofile)
{
for (size_t i=0; i<cap; i++)
{
Node* n=table[i];
ofile<<"hash "<<i<<":";
while (n!=NULL)
{
ofile<<" "<<n->item;
n=n->next;
}
}
}
};
【问题讨论】: