C++ unordered_map无法使用pair作为key的解决办法

最近在使用STL中unordered_map这种容器的时候发现无法将key设置为pair类型,编译报错信息为:

error: implicit instantiation of undefined template 'std::__1::hash<std::__1::pair<int, int> >

查了下资料才发现unordered_map中没有针对pair的hash函数,需要手动传入一个hash函数。hash函数的一种简单实现如下:

struct hash_pair { 
    template <class T1, class T2> 
    size_t operator()(const pair<T1, T2>& p) const
    { 
        auto hash1 = hash<T1>{}(p.first); 
        auto hash2 = hash<T2>{}(p.second); 
        return hash1 ^ hash2; 
    } 
}; 

接下来把这个hash函数传给unordered_map就OK了!

unordered_map<pair<int,int>, int, hash_pair> um;

因为map容器并不需要hash函数,所以将key设置为pair是不会报错的。在数据量不大的情况下,也可以考虑使用map替代unordered_map,性能并不会有太大差异。

原创文章 3 获赞 0 访问量 90

猜你喜欢

转载自blog.csdn.net/hxy1996520/article/details/105876960