c++hashstringcstring

How can I hash a string to an int using c++?


I have to write my own hash function. If I wanted to just make the simple hash function that maps each letter in the string to a numerical value (i.e. a=1, b=2, c=3, ...), is there a way I can perform this hash on a string without having to first convert it to a c-string to look at each individual char? Is there a more efficient way of hashing strings?


Solution

  • Re the first question, sure, e.g, something like:

    int hash = 0;
    int offset = 'a' - 1;
    for(string::const_iterator it=s.begin(); it!=s.end(); ++it) {
      hash = hash << 1 | (*it - offset);
    }
    

    regarding the second, there are many better ways to hash strings. E.g., see here for a few C examples (easily translatable to C++ along the lines of the snippet above).