在C ++中添加哈希表?

时间:2015-10-01 04:27:01

标签: c++ hash

猜测我做了一些愚蠢的错误,但似乎无法在现有的堆栈溢出问题中找到答案。我试图在编程类中实现一个包含C ++字符串列表的简单哈希表。我的add()函数似乎在函数内部正常工作,但是一旦我从contains()函数中检查哈希表的内容,就会发现某些东西出了问题。

void string_set::add(const char *s) { 

//copy s into new char array str
char str[strlen(s)];
strcpy(str, s);
//find hash value of string
int hValue = string_set::hash_function(s);

//create new node to contain string
node* newNode = new node();
newNode->s = str;

//if string's position in hash table is empty, add directly and 
//set newNode's next to null. if not, set newNode next to 
//current first node in list and then add to hash table
if(hash_table[hValue] == NULL) {
    hash_table[hValue] = newNode;
    newNode->next = NULL;
} else {
    newNode->next = hash_table[hValue];
    hash_table[hValue] = newNode;
}
cout << "string added: " << hash_table[hValue]->s << endl;

return;
}

这将打印预期的字符串;即如果我添加&#34; e&#34;它打印&#34; e&#34;。 但是当我在紧接着之后立即打电话:

int string_set::contains(const char *s) {
//find hash value of string
int hValue = string_set::hash_function(s);

//return inital value of hash table at that value
cout << "hash table points to " << hash_table[hValue]->s << endl;
}

打印一些垃圾。我做了什么?

由于这是针对一个类,因此提供了规范,我没有机会改变哈希表的设置方式。我稍后会添加异常等,只是想让add函数正常工作。谢谢!

编辑:抱歉,新的堆栈溢出并且不确定注释格式!是的,我可以使用std :: string。哈希函数如下

int string_set::hash_function(const char *s) {
int cValue =0;
int stringSum = 0; 
unsigned int i = 0;
for(i = 0; i < strlen(s); i++) {
    cValue = (int) s[i];
    stringSum = stringSum + cValue;
}
stringSum = stringSum % HASH_TABLE_SIZE;
return stringSum;
}

1 个答案:

答案 0 :(得分:1)

您正尝试在其功能范围之外使用局部变量。这是C ++中未定义的行为。在您的编译器实现中,堆栈帧无效,因此所有newNode->s指针变为悬空,内存,它们指向,已经用于存储不同的堆栈帧。要解决此问题,您可以在堆上动态分配内存,也可以使用std::string代替char*,这是最好的方法。

值得指出的是,标准C ++库已经具有哈希表实现std::unordered_map

相关问题