Can I use Pairs as Keys in Unordered Maps?
In C , you can encounter a compilation error when using an unordered_map with pair as its key. The issue arises from utilizing a custom type as the key, without providing an appropriate hash function for it.
Understanding the Error
The error you encounter is because unordered_map relies on a hashing mechanism to efficiently locate key-value pairs. However, it lacks a default hash function for complex types like pairs. The error message indicates that the compiler cannot implicitly instantiate an undefined hash function for your pair key type.
Solution: Providing a Hash Function
To resolve this issue, you need to define a hash function that calculates a unique hash value for your Vote pair type. This function should accept a pair as an argument and output a hash value.
Here's an example hash function implementation:
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; } };
With this hash function, you can modify your code to create an unordered_map that uses pairs as keys:
using Vote = std::pair<std::string, std::string>; using Unordered_map = std::unordered_map<Vote, int, pair_hash>;
Now, you can use this unordered_map as intended, avoiding the compilation error.
The above is the detailed content of Can I Use Pairs as Keys in C Unordered Maps, and How?. For more information, please follow other related articles on the PHP Chinese website!