gpt4 book ai didi

c++ - 在 C++ 中添加到哈希表?

转载 作者:行者123 更新时间:2023-11-28 06:03:12 24 4
gpt4 key购买 nike

我猜我正在做一些愚蠢的简单错误,但似乎无法在现有的堆栈溢出问题中找到答案。我正在尝试为一个编程类实现一个简单的哈希表,其中包含 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;
}

这会打印预期的字符串;即,如果我添加“e”,它会打印“e”。但是当我之后立即调用它时:

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;
}

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

因为这是一个类,已经提供了规范,我没有机会更改哈希表的设置方式。我稍后会添加异常等,只是想让添加功能正常工作。谢谢!

编辑:抱歉,堆栈溢出的新手,不确定评论格式!是的,我可以使用 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;
}

最佳答案

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

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

关于c++ - 在 C++ 中添加到哈希表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32879456/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com