映射v.s.unordered_map中可允许的密钥类型

Admissible type of key in map v.s. unordered_map

本文关键字:密钥 类型 unordered map 映射      更新时间:2023-10-16

我知道unordered_map<T, int>在从键O(1(检索值时比map<T, int>在性能方面更高效。

然而,我发现unordered_map<T, int>支持的类型不如map<T, int>那么多。

例如,map<pair<int, int>, int>可以,但unordered_map<pair<int, int>, int>不可以。

我想知道这其中有什么潜在的困难吗?如果考虑性能,我可以使用什么数据结构来获得具有O(1(性能的密钥类型对的哈希表。

您可以定义一个自定义哈希函数:

#include <unordered_map>
typedef std::pair<int,int> int_pair;
class MyHashFunc {
    std::hash<int> int_hash_func;
    public:
        long operator()(const int_pair &k) const{
            return (int_hash_func(k.first) << 16) + (int_hash_func(k.second));
        }
};
int main() {
    std::unordered_map<int_pair, int, MyHashFunc> m;
    return 0;
}

它之所以不能开箱即用,是因为类型pair<T,T>没有定义哈希函数,而unordered_map本质上是一个哈希映射,所以它的键必须是可哈希的

unordered_map<pair<int, int>, int>没有根本问题。问题是,您需要提供哈希函数比较函数

关于<pair,pair>的具体情况,请参阅此问题作为关键,关于一般情况的更多详细信息,请参阅本答案。

如果您可以提供一种从pair<int, int>生成哈希的方法,那么您就可以使用它。

示例:

#include <unordered_map>
#include <utility>
using namespace std;
struct IntPairHash
{
   size_t operator()(pair<int, int> const& p)
   {
      // If you have a 64 bit platform where sizeof(size_t) == 64
      // and sizeof(int) == 32, you can use:
      size_t h = p.second;
      h <<= 32;
      h += p.first;
      return h;
      // For other platforms, a more different approach to come up with
      // a hash value for p must be devised.
   }
};
void foo()
{
   unordered_map<pair<int, int>, int, IntPairHash> a;
}