Hash function for a vector of a pair <int, int>
I am trying to implement unordered_map for a vector <pair <int, int โ. Since there is no such hash function by default , I tried to imagine my own function:
struct ObjectHasher
{
std::size_t operator()(const Object& k) const
{
std::string h_string("");
for (auto i = k.vec.begin(); i != k.vec.end(); ++i)
{
h_string.push_back(97+i->first);
h_string.push_back(47); // '-'
h_string.push_back(97+i->second);
h_string.push_back(43); // '+'
}
return std::hash<std::string>()(h_string);
}
};
The main idea is to change the list of integers, for example ((97, 98), (105, 107)) into a formatted string such as "ab + ik" and calculate its hash thanks to the hash, string> () . I chose numbers 97, 48, and 43 only to allow the hash string to be displayed easily in the terminal during my tests.
, , - . , , push_back(), 255, , ... , :
- (1) - ok ?
- (2) - ok /?
- (3) , -?
- (4)... - ?
, , "hash in" integer. โโ boost:
template <class T>
inline void hash_combine(std::size_t& seed, const T& v)
{
std::hash<T> hasher;
seed ^= std::hash<T>(v) + 0x9e3779b9 + (seed<<6) + (seed>>2);
}
:
struct ObjectHasher
{
std::size_t operator()(const Object& k) const
{
std::size_t hash = 0;
for (auto i = k.vec.begin(); i != k.vec.end(); ++i)
{
hash_combine(hash, i->first);
hash_combine(hash, i->second);
}
return hash;
}
};
This is absolutely the right decision. All functions A hash function is a sequence of bytes and combining the contours of your elements as a string that provides a unique representation of the bytes of the map.
Of course, this can become naughty if your map contains a large number of elements.