【发布时间】:2015-07-30 23:02:20
【问题描述】:
我正在尝试使用哈希表实现一个简单的 adt,我能够将数据对象插入到它们各自的索引中。当我尝试检查 table[index]->data.GetName() 中的值时,程序崩溃了。
数据类:
Data(string name, string value int value = 0) : name(name), value(value)
{
}
string Data::GetName() const
{
return name;
}
string Data::GetValue() const
{
return value;
}
哈希表类
class HashT
{
public:
HashT(ostream&) : size(0), cap(TBL_CAP), table(new hashnode*[TBL_CAP])
{
for (int i = 0; i < cap; ++i)
{
table[i] = NULL;
}
};
HashT()
{
};
//~HashT();
void HashT::Ins(Data& data)
{
size_t index = HashFunc(data.GetName());
node * newData = new node(data);
//if (table[index]->item.GetName() == data.GetName())
// Do not insert;
else
newData->next = table[index];
table[index] = newData;
size++;
}
int HashFunc(string name);
private:
struct hashnode
{
Data item;
hashnode* next;
node(const Data& DataObj) : item(DataObj), next(NULL)
{
}
};
hashnode ** table;
int size;
Data data;
int cap;
const static int TBL_CAP = 3;
};
当我调试时,程序在item 尝试通过table[index]->item.GetName() 执行GetName() 时崩溃,如果我这样做table[index]->item.GetName(),程序也会崩溃。如果我测试table[index] == NULL,我不会收到任何错误。
【问题讨论】: