I am looking for a hash function in c++ to hash a string to an int. I used CMapStringToPtr but it has a function called "GetNextAssoc" that allows retrieving the key as string, meaning that the string must be stored and it gets so much memory. Is there any other hash function that gets less memory and does not store the string?
hashCode() method of String class can be used to convert a string into hash code. hashCode() method will return either negative or positive integer hash values. The returned hash value cannot be re-converted back to string once hashed.
Types of a Hash Function In C In this method, the hash function is dependent upon the remainder of a division. Example: elements to be placed in a hash table are 42,78,89,64 and let's take table size as 10.
A Hash Value (also called as Hashes or Checksum) is a string value (of specific length), which is the result of calculation of a Hashing Algorithm. Hash Values have different uses.
A Hash function is a function that maps any kind of data of arbitrary size to fixed-size values. The values returned by the function are called Hash Values or digests.
C++ has a built in hash function for this purpose - its used for all STL hash containers.
std::hash
PS: you can make your own too, just pass the string by const reference and cycle through its characters one by one, adding them to an integer, then mod by some value :)
int hash( const string &key, int tableSize) {
int hashVal = 0;
for(int i = 0; i<key.length(); i++)
hashVal = 37*hashVal+key[i];
hashVal %= tableSize;
if(hashVal<0)
hashVal += tableSize;
return hashVal;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With