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:

    Every age, every culture, every custom and tradition has its own character, its own weakness and its own strength, its beauties and cruelties; it accepts certain sufferings as matters of course, puts up patiently with certain evils. Human life is reduced to real suffering, to hell, only when two ages, two cultures and religions overlap.
    Hermann Hesse (1877–1962)

    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)