我正在尝试构建一个哈希表,并根据我使用在线教程学到的知识编写了以下代码
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
const int SIZE = 100;
int hash(string);
class Node
{
public:
Node();
Node(string);
int hash(int value);
private:
string data;
Node* next;
friend class HashTable;
};
Node::Node() {
data = "";
next = NULL;
}
Node::Node(string) {
data = "";
next = NULL;
}
int Node::hash(int value) {
int y;
y = value % SIZE;
}
class HashTable {
public:
HashTable();
HashTable(int);
~HashTable();
void insertItem(string);
bool retrieveItem(string);
private:
Node* ht;
};
HashTable::HashTable() {
ht = new Node[SIZE];
}
HashTable::HashTable(int max) {
ht = new Node[max];
}
HashTable::~HashTable() {
delete[] ht;
}
void HashTable::insertItem(string name) {
int val = hash(name);
for (int i = 0; i < name.length(); i++)
val += name[i];
}
bool HashTable::retrieveItem(string name) {
int val = hash(name);
if (val == 0 ) {
cout << val << " Not Found " << endl;
}
else {
cout << val << "\t" << ht->data << endl;
}
}
void print () {
//Print Hash Table with all Values
}
int main() {
HashTable ht;
ht.insertItem("Allen");
ht.insertItem("Tom");
ht.retrieveItem("Allen");
//data.hash(int val);
//cout << ht;
system("pause");
return 0;
}
int hash(string val) {
int key;
key = val % SIZE;
}
我正在尝试插入字符串值并使用 retrieveItem 函数验证名称是否存在。 另外,我该如何打印带有值的 HashTable。
我们将不胜感激任何帮助。
维什
最佳答案
这里有点不对劲。随便看一眼代码中间的一个地方,我发现:
Node::Node(string) {
data = "";
next = NULL;
}
这不会保存传入的字符串的值。我猜你真的想要更像的东西:
Node::Node(string value) : data(value), next(NULL) {}
接下来我看到的是:
int Node::hash(int value) {
int y;
y = value % SIZE;
}
这会计算一个值并将其放入 y
(局部变量)但不会返回任何内容,因此您计算的值会立即丢失。如果你试图使用它的返回值,你会得到未定义的行为(实际上,我记不太清楚——似乎在 C 中你只有在尝试使用返回值时才会得到 UB,但在 C++ 中它是 UB这一点——不管技术细节如何,它显然不是你想要的,需要修复)。
就像我说的,我只是看了一眼代码中的一个地方,然后发现——我怀疑它们是唯一的问题。最重要的是,您可能需要稍微回顾一下,弄清楚每个功能应该做什么,然后一个一个地检查它们并确保每个功能都在做它应该做的事情。
另外一点建议:我没有自己处理动态分配数组,而是使用了 std::vector
。
关于C++ 哈希链接函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10573392/