Skip to content

Instantly share code, notes, and snippets.

@odeblic
Last active May 6, 2020 13:58
Show Gist options
  • Save odeblic/7c2ae2c3e0f711c8ae6ad5b1cf983b5c to your computer and use it in GitHub Desktop.
Save odeblic/7c2ae2c3e0f711c8ae6ad5b1cf983b5c to your computer and use it in GitHub Desktop.
Add the missing hash function for pairs in the standard.
#include <string>
#include <unordered_map>
namespace std {
template <typename F, typename S>
struct hash<std::pair<F, S>>
{
std::size_t operator()(std::pair<F, S> const &p) const
{
return std::hash<F>{}(p.first) ^ (std::hash<S>{}(p.second) << 1);
// other hashing options:
// return std::hash<F>{}(p.first) ^ std::hash<S>{}(p.second);
// return std::hash<F>{}(p.first) + std::hash<S>{}(p.second) + 1;
// further information about hash function:
// https://stackoverflow.com/questions/5889238/why-is-xor-the-default-way-to-combine-hashes
}
};
};
int main()
{
typedef std::pair<int, std::string> Key;
typedef short Value;
auto p1 = Key(33, "France");
auto p2 = Key(44, "England");
auto p3 = Key(852, "Hong Kong");
std::hash<Key>{}(p1);
std::hash<Key>{}(p2);
std::hash<Key>{}(p3);
std::unordered_map<Key, Value> container;
container.insert(std::make_pair<Key, Value>(std::move(p1), 100));
container.insert(std::make_pair<Key, Value>(std::move(p2), 200));
container.insert(std::make_pair<Key, Value>(std::move(p3), 300));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment