【发布时间】:2012-05-13 16:37:44
【问题描述】:
我正在尝试构建一个哈希表,根据我使用在线教程学到的知识,我想出了以下代码
#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。
我们将不胜感激。
维什
【问题讨论】:
-
我的代码不起作用!代码的哪一部分是错误的?或者如果整个代码都错了,解决办法是什么?
-
错的地方很多;如果你有两个构造函数并且不保存长度,你怎么知道数组有多大?你为什么要在字符串上使用模数?您实际上并没有在
insertItem中插入任何内容,也没有在retrieveItem中返回任何内容。 -
我想使用模来获取字符串的 ascii 值,并使用 ascii total % size = index position in table 并将字符串存储在那里。例如对于字符串“Allen”,总 ascii 值为 476 % 101(表大小)给我 76 作为索引表中存储数据的位置。
-
转向像
const std::string&这样的方法签名,而不是string。using namespace stdis something you'll want to avoid,它会引起很多混乱和冲突。传递const引用可避免重复参数和意外突变。
标签: c++ function hashtable chaining