Hashing a string to an integer in c++

c++, hash, string, type-conversion

Solution

C++11 introduces an implementation defined hashing function called `std::hash` in header `<functional>` which has speciality for the string classes `std::string`, `std::wstring`, etc.

It's as simple as doing this:

#include <iostream>
#include <functional> //for std::hash
#include <string>

int main() {
    std::string str = "Hello World";
    std::hash<std::string> hasher;
    auto hashed = hasher(str); //returns std::size_t
    std::cout << hashed << '\n'; //outputs 2146989006636459346 on my machine
}

Specializing `std::hash` for your user defined types isn't very complex either. Do note however that there is no `std::hash` specialization for `const char*` or any of the C-strings.

Problem

I am trying to figure out the conversion process for strings to ints. We are doing a program with hashing, in which the key value to be hashed is the name of a state. From my research, it seems like atoi() will not work. Do I need to break each letter of the word down and individually convert? Do I use ASCII? Am I completely going in the wrong direction? I am very lost, so ANY information would be fantastic. Thanks!

Original source