Andrei
Andrei

Reputation: 1

hash function for every data type

On my data structures class i have to implement an hash table. I managed to implement the hash function like this:

size_t hashFunction(const string &key)
    {
        size_t h = 37;
        for (char c: key)
        {
            h = (h * 54059) ^ (c * 76963);
        }
        return h % 86969 % buckets;
    }
template<class T>
size_t hashFunction(const T &key)
    {
        return ((key * 54059) ^ (key * 76963)) % 86969 % buckets;
    }

but my teacher only wants me to have a single hash function for every data type, how can i achieve that?

Upvotes: 0

Views: 1070

Answers (1)

eerorika
eerorika

Reputation: 238431

Here is one that works with all types:

template<class T>
std::size_t hashFunction(const T&)
{
    return 0;
}

It isn't very good and I wouldn't recommend using it for anything. But it achieves the goal of working with all types.

You can get better hashing with type specific hash functions, which I would recommend doing.

Upvotes: 2

Related Questions