unordered_map散列函数c ++ [英] unordered_map hash function c++

查看:206
本文介绍了unordered_map散列函数c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要定义一个unordered_map像这样 unordered_map< pair< int,int>,* Foo> ,定义和传递 hash 等于的函数?

I need to define an unordered_map like this unordered_map<pair<int, int>, *Foo>, what is the syntax for defining and passing a hash and equal functions to this map?

到此对象:

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
什么是正确的方法呢?
感谢。

I have no Idea what is the size_type_Buskets means so I gave it 1. What is the right way to do it? Thanks.

推荐答案

这是C ++ 11中不幸的遗漏; Boost有 hash_combine 的答案。随意地从他们粘贴它们!下面是我如何哈希对:

This is an unfortunate omission in C++11; Boost has the answer in terms of hash_combine. Feel free to just paste it from them! Here's how I hash pairs:

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 作为许多其他事情的基础,如元组和范围,所以你可以hash整个(有序)容器,只要每个成员是单独hashable。

You can use hash_combine as the basis for many other things, like tuples and ranges, so you could hash an entire (ordered) container, for example, as long as each member is individually hashable.

现在你只需要声明一个新的地图:

Now you can just declare a new map:

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






如果您想使用自制哈希没有好的统计属性),你必须明确指定模板参数:


If you want to use your homebrew hasher (which hasn't got good statistical properties), you have to specify the template parameters explicitly:

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

注意,没有必要指定哈希对象的副本,默认是default-为你构建一个。

Note that there's no need to specify a copy of a hasher object, as the default is to default-construct one for you.

这篇关于unordered_map散列函数c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆