C++ - Hash combine example for hash function in unordered_map

less than 1 minute read

1
2
3
4
5
6
template <class T>
inline void hash_combine(std::size_t & seed, const T & v)
{
  std::hash<T> hasher;
  seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Item
{
public:
    std::string name;
    int age;
    int code;
    Item(std::string n, int age, int code)
	: name(std::move(n)), age(age), code(code)
    {
    }
    bool operator == (Item const& item) const
    {
	return name == item.name &&
		age == item.age &&
		code == item.code;
    }
};
struct ItemHasher
{
    std::size_t operator()(Item const& item) const
    {
	std::size_t seed = 0;
	hash_combine(seed, item.name);
	hash_combine(seed, item.age);
	hash_combine(seed, item.code);
	return seed;
    }
};
std::unordered_map<Item, std::string, ItemHasher> testHash;