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:

    Parents fear lest the natural love of their children may fade away. What kind of nature is that which is subject to decay? Custom is a second nature which destroys the former. But what is nature? For is custom not natural? I am much afraid that nature is itself only a first custom, as custom is a second nature.
    Blaise Pascal (1623–1662)

    Mark the babe
    Not long accustomed to this breathing world;
    One that hath barely learned to shape a smile,
    Though yet irrational of soul, to grasp
    With tiny finger—to let fall a tear;
    And, as the heavy cloud of sleep dissolves,
    To stretch his limbs, bemocking, as might seem,
    The outward functions of intelligent man.
    William Wordsworth (1770–1850)