【问题标题】:Trouble creating custom hash function unordered_map?创建自定义哈希函数 unordered_map 时遇到问题?
【发布时间】:2015-02-05 22:47:45
【问题描述】:

我想为无序地图创建一个自定义散列函数。我发现了这个问题:C++ unordered_map fail when used with a vector as key,发现如果在无序映射中使用向量作为键,则需要创建自己的哈希函数。我尝试复制这样写的哈希函数:

template <typename Container> 
struct container_hash {
    std::size_t operator()(Container const& c) const {
        return boost::hash_range(c.begin(), c.end());
    }
};

但是当我尝试使用我的键创建一个 unordered_map 作为整数向量时,如下所示:,

unordered_map<vector<int>, int, container_hash<vector<int>>> hash;

我收到一个问题:

error: declaration of ‘struct std::hash<std::vector<int> >’

我尝试了其他方法将 container_hash 函数包含到我的 unordered_map 的实现中,例如

unordered_map<vector<int>, int, container_hash> hash;

但我再次收到另一个错误消息:

type/value mismatch at argument 3 in template parameter list for ‘template<class _Key, class _Tp, class _Hash, class _Pred, class _Alloc> class std::unordered_map’

我真的不知道如何解决这个问题,如果有人可以帮助我,那就太好了!谢谢!

【问题讨论】:

  • 什么编译器? gcc 和 clang accept 你的第一个定义。
  • 我正在尝试使用 MPI 编写程序,所以我使用的是 mpicxx 编译器@Praetorian
  • 看看它是否会编译我链接的代码,如果不是,那可能是那个编译器的问题。
  • @Praetorian 有趣的是它确实可以编译。我认为我与您在链接的代码中编写的内容没有什么不同。
  • @Praetorian 啊没关系。我发现了这个问题。它在我的代码中的其他地方。很抱歉,非常感谢你帮助我解决这个问题。

标签: c++ boost unordered-map hash-function


【解决方案1】:

此代码compiles just fine:

#include <vector>
#include <boost/unordered_map.hpp>

template <typename Container>
struct container_hash {
    std::size_t operator()(Container const& c) const {
    return boost::hash_range(c.begin(), c.end());
    }
};

int main()
{
    boost::unordered_map
        <std::vector <int>, int,
         container_hash <std::vector  <int> > > foo;
    return 0;
}

您的问题可能在其他地方。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-15
    • 1970-01-01
    • 1970-01-01
    • 2020-08-23
    • 2013-03-07
    • 1970-01-01
    • 2011-11-05
    • 2010-10-22
    相关资源
    最近更新 更多