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:

    She was custom built for the pictures—teeny tiny, one inch less than five foot, and a perfectly enormous head. Her face went right from one side of the screen to the other. Gloria Swanson was like that, as well. Joan Crawford, too. You need the big face, for the closeups.
    Angela Carter (1940–1992)

    Nobody is so constituted as to be able to live everywhere and anywhere; and he who has great duties to perform, which lay claim to all his strength, has, in this respect, a very limited choice. The influence of climate upon the bodily functions ... extends so far, that a blunder in the choice of locality and climate is able not only to alienate a man from his actual duty, but also to withhold it from him altogether, so that he never even comes face to face with it.
    Friedrich Nietzsche (1844–1900)