Unordered Associative Containers (C++) - Custom Hash Functions

Custom Hash Functions

In order to use custom objects in std::unordered_map, a custom hash function must be defined. This function takes a const reference to the custom type and returns a size_t

struct X{int i,j,k;}; struct hash_X{ size_t operator(const X &x) const{ return hash(x.i) ^ hash(x.j) ^ hash(x.k); } };

The user defined function can be used as is in std::unordered_map, by passing it as a template parameter

std::unordered_map my_map;

Or can be set as the default hash function by specializing the std::hash function

namespace std { template <> class hash{ public : size_t operator(const X &x ) const{ return hash(x.i) ^ hash(x.j) ^ hash(x.k); } }; } //... std::unordered_map my_map;

Read more about this topic:  Unordered Associative Containers (C++)

Famous quotes containing the words custom and/or functions:

    The New Year is the season in which custom seems more particularly to authorize civil and harmless lies, under the name of compliments. People reciprocally profess wishes which they seldom form and concern which they seldom feel.
    Philip Dormer Stanhope, 4th Earl Chesterfield (1694–1773)

    The English masses are lovable: they are kind, decent, tolerant, practical and not stupid. The tragedy is that there are too many of them, and that they are aimless, having outgrown the servile functions for which they were encouraged to multiply. One day these huge crowds will have to seize power because there will be nothing else for them to do, and yet they neither demand power nor are ready to make use of it; they will learn only to be bored in a new way.
    Cyril Connolly (1903–1974)