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:

    People who love only once in their lives are ... shallow people. What they call their loyalty, and their fidelity, I call either the lethargy of custom or their lack of imagination. Faithfulness is to the emotional life what consistency is to the life of the intellect—simply a confession of failures.
    Oscar Wilde (1854–1900)

    One of the most highly valued functions of used parents these days is to be the villains of their children’s lives, the people the child blames for any shortcomings or disappointments. But if your identity comes from your parents’ failings, then you remain forever a member of the child generation, stuck and unable to move on to an adulthood in which you identify yourself in terms of what you do, not what has been done to you.
    Frank Pittman (20th century)