Home >Backend Development >C++ >How to Resolve Unordered Map Compilation Errors with Pair Keys?
Unordered Map Compilation Error with Pair Keys
When attempting to create an unordered map where the keys are pairs, you may encounter the following error:
Implicit instantiation of undefined template 'std::__1::hash, std::__1::basic_string >>'
This error occurs because unordered maps require hash functions to be defined for their key types. While the hash
Solution: Providing a Custom Hash Function
To resolve this issue, you need to define a custom hash function for your pair key type. Here's an example implementation:
struct pair_hash { template<class T1, class T2> size_t operator()(const pair<T1, T2>& p) const { auto h1 = hash<T1>()(p.first); auto h2 = hash<T2>()(p.second); return h1 ^ h2; } };
This hash function combines the hash values of the individual components of the pair using bitwise XOR (^).
Using the Custom Hash Function
Once you have defined the hash function, you can use it to create an unordered map with pair keys as follows:
using Vote = pair<string, string>; using Unordered_map = unordered_map<Vote, int, pair_hash>; Unordered_map um;
With this modification, the compilation error will no longer occur, and you will be able to use the unordered map as expected.
The above is the detailed content of How to Resolve Unordered Map Compilation Errors with Pair Keys?. For more information, please follow other related articles on the PHP Chinese website!