Why can't I compile an unordered_map with a pair as key?
The issue faced here is the absence of a suitable hash function for the key type. To resolve this, provide a custom hash function for the pair key. Here's an example:
#include <unordered_map> #include <functional> #include <string> #include <utility> 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; // Simple example, for better results use boost.hash_combine } }; using Vote = std::pair<std::string, std::string>; using Unordered_map = std::unordered_map<Vote, int, pair_hash>;
With this custom hash function, you can now create an unordered_map
The above is the detailed content of Why Can't I Use `std::pair` as the Key in an `std::unordered_map` and How Do I Fix It?. For more information, please follow other related articles on the PHP Chinese website!