#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
using namespace std;
class Item {
public:
Item(const string & v): value(v), next(0) { }
string value;
Item * next;
};
int hash_function(const string & s)
{
unsigned int hashval = 0;
int i = s.length();
while (i > 0)
{
hashval += s[--i];
}
return hashval%101;
}
main()
{
string name;
int index;
Item * p;
vector<Item *> bucket(101);
for (index = 0; index < 101; index++)
bucket[index] = 0;
while (cin >> name) {
p = new Item(name);
index = hash_function(name);
// push front
if (bucket[index] != 0)
p->next = bucket[index];
bucket[index] = p;
}
for (index = 0; index < 101; index++)
if (bucket[index] != 0) {
cout << setw(3) << index << ": ";
p = bucket[index];
while (p != 0) {
cout << p->value << " ";
p = p->next;
}
cout << endl;
}
Item * temp;
for (index = 0; index < 101; index++) {
p = bucket[index];
while (p != 0) {
temp = p;
p = p->next;
delete temp;
}
}
}
它包含兩個非常簡單的散列函數。我正在努力研究未被評論的那個,因爲它在測試時似乎是兩者中較好的一個。我想要一組輸入的名字均勻地分佈在它自己的存儲桶中,目前看起來似乎正在工作,除了以相同字母開頭的名稱之外。例如,艾米和愛麗絲將出現在同一個桶中,依此類推。創建一個更好的散列函數
這裏是一個示例輸入/輸出:
Alice
Amy
Barry
Carrie
David
Garret
Edward
Henry
Ingrid
Fred
65: Amy Alice
66: Barry
67: Carrie
68: David
69: Edward
70: Fred
71: Garret
72: Henry
73: Ingrid
我可以添加到我的算法,將允許艾米和愛麗絲什麼要放置在自己的桶?
請提供有效的代碼。你的'hash_function'不返回任何東西,'main'沒有返回類型。切換到更好的編譯器可能會有幫助。 – ybungalobill 2011-03-20 21:58:35
手動計算您記住的一個示例名稱的散列函數,並將其與您上面發佈的數據進行比較。 – 2011-03-20 22:08:02