hash_map<向量<int>,int> 使用查找函数时出错

hash_map< vector<int>, int> error when using find function

本文关键字:gt lt int 查找 函数 出错 向量 hash map      更新时间:2023-10-16
struct HASH_CMP {
    bool operator()(vector<int> V, vector<int> W) const {
        for(int i = 0; i < 10; i++)
            if(V[i] != W[i]) return false;
        return true;
    }
};
hash_map< std::vector<int>, int, HASH_CMP > H;
long long inHash(const vector<int> &V) {
    if(H.find(V) == H.end()) return -1; //this line
    return H[V];
}

我已经声明了下面的哈希值,给出了上面的比较类,我在上面提到的行收到了一个错误:

不匹配调用' (const HASH_CMP) (const std::vector<int, std::allocator<int> >&)

我需要一些帮助来修复这个代码。

第三个模板参数是哈希函函数。比较函子是第四个模板实参。因此,您需要:

hash_map<std::vector<int>, int, HASH_HASH, HASH_CMP>

你还需要写HASH_HASH

(我建议你看看Boost的hash_range实现的灵感。)还要注意,向量的相等性已经定义(并且比您的版本更有效),不应该需要自己编写代码。

正如错误告诉您的那样,您需要一个散列函数,该函数接受const std::vector<int>&并返回size_t。要把某个东西放到哈希映射中,必须有某种方法对它进行哈希。

size_t operator()(const vector<int>& vec)
{
    size_t v = 0;
    for (vector<int>::const_iterator it = vec.begin(); it != vec.end(); ++it)
        v = (v ^ *it) * 0x9e3779b9;
    return v;
}