#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;
}
}
}
두 개의 매우 간단한 해시 함수가 포함되어 있습니다. 내가 테스트 할 때 두 사람 중 더 나은 것 같아서, 나는 주석 처리되지 않은 것에 대해 연구하려고 노력하고있다. 나는 동일한 문자로 시작하는 이름을 제외하고는 입력 된 이름 집합이 자신의 버킷에 균등하게 배분되고 지금까지는 작동하고있는 것처럼 보이기를 원합니다. 예를 들어 Amy와 Alice는 같은 버켓에 나타납니다.더 나은 해시 함수 만들기
나는 에이미와 앨리스를 허용 할 내 알고리즘에 추가 할 수있는 무엇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
하나의 예제 이름을 염두에두고 해시 함수를 계산하고이를 위에서 게시 한 데이터와 비교하십시오. –