How to Store a Hashed Value

Hash functions and tables are a bit confusing. I'm trying to understand how to store a string as a hashed value into an array with a max of 7 elements, and output which location the hash is stored as a string. So for example:

 
cout << value << " has been stored in " << location[length];

How would I get the program to output each location[length] as a unique string based on what the value is?
How would the program know which location to store a hashed value?

This is what I have come up with so far:

1
2
3
cout << "Enter name of person to add: ";
cin >> userInput;
system.AddName(userInput);


1
2
3
4
5
6
7
8
9
10
11
12
13
class ThemePark
{
private:
 int hashValue;
 int hashSize;
 int MAX_SIZE;
 int location[7]; //represents the rides
 int length;
public:
 ThemePark();
 void Hash(const string&); //hash function
 void AddName(const string&); //adds a person to a queue
};


1
2
3
4
5
6
7
ThemePark::ThemePark() //constructor
{
 MAX_SIZE = 7;
 hashValue = 0;
 hashSize = MAX_SIZE; //max size is 7
 length = 0;
}


1
2
3
4
5
6
7
8
9
10
11
void ThemePark::Hash(const string& value)
{
 int strLength = value.length(); //length of the string
 hashValue = 0;
 for(unsigned int index = 0; index < strLength; index++) {
  hashValue = (hashValue * 31) + value[index];
  hashValue %= hashSize; //hashValue = the remainder of hashValue / hashSize
 }
 location[length] = hashValue;
 length++;
}


1
2
3
4
5
void ThemePark::AddName(const string& value)
{
 Hash(value);
 cout << value << " successfully added to " << hashValue;
}
Last edited on
closed account (o3hC5Di1)
Hi there,

Hashing functions is something I would personally not try and reinvent the wheel due to their complexity.
PolarSSL provides the source code for all their implementations, I made a topic about a C++ wrapper for their SHA4 algorithm a while ago, perhaps it is of use to you: http://www.cplusplus.com/forum/general/98605/

Hope that helps.

All the best,
NwN
Thanks for the input. I managed to figure it out after reading this on http://en.wikipedia.org/wiki/Hash_table#Hashing

1
2
3
hash = hashfunc(key)

index = hash % array_size
Topic archived. No new replies allowed.