22

我需要像这样定义一个 unordered_map unordered_map<pair<int, int>, *Foo>,定义和传递 a hashandequal函数到这个映射的语法是什么?

我尝试将这个对象传递给它:

class pairHash{
public:
    long operator()(const pair<int, int> &k) const{
        return k.first * 100 + k.second;
    }
};

没有运气:

unordered_map<pair<int, int>, int> map = unordered_map<pair<int, int>, int>(1,
*(new pairHash()));

我不知道是什么size_type_Buskets手段,所以我给了它1。正确的方法是什么?谢谢。

4

3 回答 3

45

这是 C++11 中不幸的遗漏;Boost 在hash_combine. 随意从他们那里粘贴它!这是我散列对的方式:

template <class T>
inline void hash_combine(std::size_t & seed, const T & v)
{
  std::hash<T> hasher;
  seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}

namespace std
{
  template<typename S, typename T> struct hash<pair<S, T>>
  {
    inline size_t operator()(const pair<S, T> & v) const
    {
      size_t seed = 0;
      ::hash_combine(seed, v.first);
      ::hash_combine(seed, v.second);
      return seed;
    }
  };
}

您可以将hash_combine其用作许多其他事物的基础,例如元组和范围,因此您可以散列整个(有序)容器,例如,只要每个成员都是单独可散列的。

现在您可以声明一个新地图:

std::unordered_map<std::pair<int, int>, my_mapped_type> mymap;

如果你想使用你的自制散列器(它没有很好的统计属性),你必须明确指定模板参数:

std::unordered_map<std::pair<int,int>, int, pairHash> yourmap;

请注意,不需要指定哈希对象的副本,因为默认情况下会为您默认构造一个。

于 2011-08-28T16:31:01.953 回答
10

哈希函数的返回类型应该是size_t,而不是long(尽管这不是错误的原因)。您为提供自定义哈希函数显示的语法不正确。

您还需要提供一个相等的谓词以使上述工作正常。

#include <unordered_map>
#include <utility>

using namespace std;

class pairHash{
public:
    size_t operator()(const pair<int, int> &k) const{
        return k.first * 100 + k.second;
    }
};

struct pairEquals : binary_function<const pair<int,int>&, const pair<int,int>&, bool> {
  result_type operator()( first_argument_type lhs, second_argument_type rhs ) const
  {
    return (lhs.first == rhs.first) && (lhs.second == rhs.second);
  }
};     

int main()
{
  unordered_map<pair<int, int>, int, pairHash, pairEquals> myMap;

  myMap[make_pair(10,20)] = 100;
  myMap.insert( make_pair(make_pair(100,200), 1000) );
}

编辑:
您不需要定义相等谓词,因为它operator==是为定义的std::pair,它完全符合我在pairEquals. pairEquals如果您希望以不同的方式进行比较,则只需要定义。

于 2011-08-28T16:32:08.557 回答
10

如果您对使用 Boost 没问题,一个更清洁的解决方案是依赖 Boost 对哈希函数的实现(实际上,这正是 kerrek-sb 在他的回答中解释的)。因此,您所要做的就是:

#include <unordered_map>
#include <boost/functional/hash.hpp>

using namespace std;
using namespace boost;

unordered_map<pair<int, int>, int, hash<pair<int, int>>> table;
于 2014-02-28T16:33:17.640 回答