Using Pairs as Keys in Unordered Maps
When attempting to declare an unordered_map where the keys are pairs (Vote = pair
Implicit instantiation of undefined template 'std::__1::hash, std::__1::basic_string > >'
This error arises because unordered_map relies on a hash function tailored to its key type. Since the default hash function is not applicable to pairs, you must provide a custom hash function.
For instance, consider the following custom hash function (pair_hash):
struct pair_hash { template <class T1, class T2> std::size_t operator() (const std::pair<T1, T2> &p) const { auto h1 = std::hash<T1>{}(p.first); auto h2 = std::hash<T2>{}(p.second); return h1 ^ h2; } };
This hash function combines the hash values of the pair's components using the XOR operator. To use it, modify the unordered_map declaration as follows:
using Vote = std::pair<std::string, std::string>; using Unordered_map = std::unordered_map<Vote, int, pair_hash>;
This approach allows the creation of unordered maps with pairs as keys by providing a suitable hash function. However, it's worth noting that this simplistic implementation may not exhibit optimal hash properties and consider exploring Boost's hash_combine function or set hash_value for improved results.
The above is the detailed content of How to Use Pairs as Keys in Unordered Maps in C ?. For more information, please follow other related articles on the PHP Chinese website!