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

前端 未结 10 1753
长发绾君心
长发绾君心 2020-12-29 07:27

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, ...), i

相关标签:
10条回答
  • 2020-12-29 08:03

    Here's a C (++) hash function that I found in Stroustrup's book:

    int hash(const char *str)
    {
        int h = 0;
        while (*str)
           h = h << 1 ^ *str++;
        return h;
    }
    

    If you're using it for a hash table (which Stroustrup does) then you can instead return the abs of the hash modulo a prime number. So instead

        return (h > 0 ? h : -h) % N_BUCKETS;
    

    for the last line.

    0 讨论(0)
  • 2020-12-29 08:03

    Another way for small strings:

    int hash(const char* str) {
        int hash = 0;
        int c = 0;
    
        while (c < std::strlen(str)) {
            hash += (int)str[c] << (int)str[c+1];
            c++;
        }
        return hash;
    }
    
    0 讨论(0)
  • 2020-12-29 08:07

    You can examine each individual char from a std::string using the [] operator. However, you can look at Boost::Functional/Hash for guidance on a better hashing scheme. There is also a list of hashing functions in c located here.

    0 讨论(0)
  • 2020-12-29 08:09

    Just posting an improvement to Arnestig's djb2 algorithm to be constexpr-friendly. I had to remove the unsigned qualifier of the argument so it can work with literal strings.

    constexpr unsigned long hash(const char *str) {
        unsigned long hash = 5381;
    
        while (int c = *str++) {
            hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
        }
    
        return hash;
    }
    
    0 讨论(0)
  • 2020-12-29 08:11

    xor the characters together, four at a time.

    0 讨论(0)
  • 2020-12-29 08:13

    C++11 ships with a standard hashing function for strings.

    https://en.cppreference.com/w/cpp/string/basic_string/hash

    #include <string>
    #include<functional> // hash
    int main(){
        std::string s = "Hello";
        std::size_t hash = std::hash<std::string>{}(s);
    }
    
    0 讨论(0)
提交回复
热议问题