#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;
}
}
}
which contains two very simple hash functions. I'm trying to work on the one which is not commented out, as it seems like the better of the two when tested. I want a set of names that is input to be distributed evenly in it's own bucket and so far, that seems to be working, with the exception of names which begin with the same letter. For example, Amy and Alice will appear in the same bucket and so on.
Here is a sample input/output:
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
What can I add to my algorithm that would allow Amy and Alice to be placed in their own bucket?
hash_functiondoesn't return anything andmaindoesn't have a return type. Switching to a better compiler may help.