Have a good hash function for a C++ hash table?

前端 未结 9 1123
鱼传尺愫
鱼传尺愫 2020-12-12 18:15

I am in need of a performance-oriented hash function implementation in C++ for a hash table that I will be coding. I looked around already and only found questions asking wh

9条回答
  •  执念已碎
    2020-12-12 18:43

    This simple polynomial works surprisingly well. I got it from Paul Larson of Microsoft Research who studied a wide variety of hash functions and hash multipliers.

    unsigned hash(const char* s, unsigned salt)
    {
        unsigned h = salt;
        while (*s)
            h = h * 101 + (unsigned) *s++;
        return h;
    }
    

    salt should be initialized to some randomly chosen value before the hashtable is created to defend against hash table attacks. If this isn't an issue for you, just use 0.

    The size of the table is important too, to minimize collisions. Sounds like yours is fine.

提交回复
热议问题