Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hash function in c++ for string to int

Tags:

c++

string

hash

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?

like image 606
Bipario Avatar asked Dec 19 '11 20:12

Bipario


People also ask

How do I convert a string to a number hash?

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.

Is there a hash function in C?

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.

What is the hash value of a string?

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.

What would the hash function return for the string?

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.


2 Answers

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 :)

like image 113
John Humphreys Avatar answered Oct 20 '22 00:10

John Humphreys


 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;
 }
like image 24
Vosobe Kapsimanis Avatar answered Oct 19 '22 22:10

Vosobe Kapsimanis