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

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);
}
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;
Advertisements
This entry was posted in C++, Programming. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s