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

前端 未结 10 1852
长发绾君心
长发绾君心 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: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;
    }
    

提交回复
热议问题