unordered_map hash function c++

后端 未结 3 1697
粉色の甜心
粉色の甜心 2020-11-27 04:14

I need to define an unordered_map like this unordered_map, *Foo>, what is the syntax for defining and passing a hash and

3条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 04:46

    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 
    inline void hash_combine(std::size_t & seed, const T & v)
    {
      std::hash hasher;
      seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
    }
    
    namespace std
    {
      template struct hash>
      {
        inline size_t operator()(const pair & v) const
        {
          size_t seed = 0;
          ::hash_combine(seed, v.first);
          ::hash_combine(seed, v.second);
          return seed;
        }
      };
    }
    

    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, 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, int, pairHash> yourmap;
    

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

提交回复
热议问题