我想建立一個哈希表,並與我所使用的在線教程我想出了下面的代碼瞭解到C++散列鏈接功能
#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。
任何幫助將不勝感激。
Vish
問題是什麼? –
我的代碼不起作用!代碼的哪部分是錯的?或者如果整個代碼都是錯誤的,那麼解決方案是什麼? – Vish
有很多錯誤;如果你有兩個構造函數並且不保存長度,你怎麼知道這個數組有多大?你爲什麼試圖在字符串上使用模數?你實際上並沒有在'insertItem'中插入任何東西,也沒有在'retrieveItem'中返回任何東西。 –