c++使用无序键组合进行映射查找

C++ using an unordered key combination for a map lookup

本文关键字:映射 查找 组合 无序 c++      更新时间:2023-10-16

我想创建一个unordered_map,其中键是两个整数的组合。由于键值的顺序在比较时将被忽略,因此我考虑使用unordered_set作为键,如下所示:

#include <unordered_set>
#include <unordered_map>
using namespace std;
int main ()
{
    unordered_set<int> key_set1 = {21, 42};
    unordered_map<unordered_set<int>, char> map;
    map[key_set1] = 'a';
    ...
    unordered_set<int> key_set2 = {42, 21};
    if(map[key_set2] == map[key_set2])
        success();
}

在编译时,它看起来像是哈希函数的一些问题:

error: no match for call to ‘(const std::hash<std::unordered_set<int> >) (const std::unordered_set<int>&)’
  noexcept(declval<const _Hash&>()(declval<const _Key&>()))>

我该如何解决这个问题?还是有更好的方法/数据结构?

没有预定义的散列函数为unordered_set,所以你必须实现自己的;这里有相关的文档http://en.cppreference.com/w/cpp/utility/hash.

基本上你需要:

// custom specialization of std::hash can be injected in namespace std
namespace std
{
    template<> struct hash<unordered_set<int>>
    {
        std::size_t operator()(unordered_set<int> const& s) const
        {
            std::size_t hash = 0;
            for (auto && i : s) hash ^= std::hash<int>()(i);
            return hash;
        }
    };
}

现在xor不是推荐的组合哈希函数的方法,但它应该在这种情况下工作,因为它既无序集合。因为它是无序的你需要一个可交换的函数。推荐的散列组合器没有此属性,因为您通常希望"abc"的散列方式与"bca"不同。其次,它是一个集合的事实保证了你不会有任何重复的元素。这可以避免您的哈希函数因为x ^ x == 0 .

而失败。

我还应该提到,您希望在cpp文件中定义它,这样您就不会将std类型上的特定哈希实现暴露给所有人。

问题是unordered_set不是为在无序容器中用作键而构建的。

如果总是恰好使用两个整型数,那么使用一对整型数作为键,并添加一个函数将两个整型数组成一个正确排序的整数对,这样会更经济:

pair<int,int> unordered_key(int a, int b) {
    return a<b?make_pair(a, b):make_pair(b, a);
}

如前所述,要直接使用std::pair作为键,您需要显式地为它定义一个哈希函数。如果你想避免这种情况,你可以把2个无符号整数按位组合成1:

uint64_t makeKey(uint32_t a, uint32_t b)
{
    return a < b ? (static_cast<uint64_t>(a) << 32) + b : (static_cast<uint64_t>(b) << 32) + a;
}
int main ()
{
    auto key_set1 = makeKey(21, 42);
    unordered_map<uint64_t, char> map;
    map[key_set1] = 'a';
    //...
    auto key_set2 = makeKey(42, 21);
    if(map[key_set1] == map[key_set2])
        std::cout << "success" << std::endl;
}

由于顺序在这里并不重要,您可以使用std::pair和自定义工厂来强制两个整数的顺序:

std::pair<int, int> make_my_pair(int x, int y) {
    return std::make_pair(std::min(x, y), std::max(x, y));
}

当然,这只会在你一直使用make_my_pair的情况下才会起作用。

或者,您可以定义自己的具有类似属性的键类。