使用自定义类类型作为键的C++ unordered_map

Alf*_*ong 258 c++ hash unordered-map g++ hashtree

我正在尝试使用自定义类作为关键字unordered_map,如下所示:

#include <iostream>
#include <algorithm>
#include <unordered_map>

using namespace std;

class node;
class Solution;

class Node {
public:
    int a;
    int b; 
    int c;
    Node(){}
    Node(vector<int> v) {
        sort(v.begin(), v.end());
        a = v[0];       
        b = v[1];       
        c = v[2];       
    }

    bool operator==(Node i) {
        if ( i.a==this->a && i.b==this->b &&i.c==this->c ) {
            return true;
        } else {
            return false;
        }
    }
};

int main() {
    unordered_map<Node, int> m;    

    vector<int> v;
    v.push_back(3);
    v.push_back(8);
    v.push_back(9);
    Node n(v);

    m[n] = 0;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是,g ++给了我以下错误:

In file included from /usr/include/c++/4.6/string:50:0,
                 from /usr/include/c++/4.6/bits/locale_classes.h:42,
                 from /usr/include/c++/4.6/bits/ios_base.h:43,
                 from /usr/include/c++/4.6/ios:43,
                 from /usr/include/c++/4.6/ostream:40,
                 from /usr/include/c++/4.6/iostream:40,
                 from 3sum.cpp:4:
/usr/include/c++/4.6/bits/stl_function.h: In member function ‘bool std::equal_to<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = Node]’:
/usr/include/c++/4.6/bits/hashtable_policy.h:768:48:   instantiated from ‘bool std::__detail::_Hash_code_base<_Key, _Value, _ExtractKey, _Equal, _H1, _H2, std::__detail::_Default_ranged_hash, false>::_M_compare(const _Key&, std::__detail::_Hash_code_base<_Key, _Value, _ExtractKey, _Equal, _H1, _H2, std::__detail::_Default_ranged_hash, false>::_Hash_code_type, std::__detail::_Hash_node<_Value, false>*) const [with _Key = Node, _Value = std::pair<const Node, int>, _ExtractKey = std::_Select1st<std::pair<const Node, int> >, _Equal = std::equal_to<Node>, _H1 = std::hash<Node>, _H2 = std::__detail::_Mod_range_hashing, std::__detail::_Hash_code_base<_Key, _Value, _ExtractKey, _Equal, _H1, _H2, std::__detail::_Default_ranged_hash, false>::_Hash_code_type = long unsigned int]’
/usr/include/c++/4.6/bits/hashtable.h:897:2:   instantiated from ‘std::_Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __cache_hash_code, __constant_iterators, __unique_keys>::_Node* std::_Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __cache_hash_code, __constant_iterators, __unique_keys>::_M_find_node(std::_Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __cache_hash_code, __constant_iterators, __unique_keys>::_Node*, const key_type&, typename std::_Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __cache_hash_code, __constant_iterators, __unique_keys>::_Hash_code_type) const [with _Key = Node, _Value = std::pair<const Node, int>, _Allocator = std::allocator<std::pair<const Node, int> >, _ExtractKey = std::_Select1st<std::pair<const Node, int> >, _Equal = std::equal_to<Node>, _H1 = std::hash<Node>, _H2 = std::__detail::_Mod_range_hashing, _Hash = std::__detail::_Default_ranged_hash, _RehashPolicy = std::__detail::_Prime_rehash_policy, bool __cache_hash_code = false, bool __constant_iterators = false, bool __unique_keys = true, std::_Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __cache_hash_code, __constant_iterators, __unique_keys>::_Node = std::__detail::_Hash_node<std::pair<const Node, int>, false>, std::_Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __cache_hash_code, __constant_iterators, __unique_keys>::key_type = Node, typename std::_Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __cache_hash_code, __constant_iterators, __unique_keys>::_Hash_code_type = long unsigned int]’
/usr/include/c++/4.6/bits/hashtable_policy.h:546:53:   instantiated from ‘std::__detail::_Map_base<_Key, _Pair, std::_Select1st<_Pair>, true, _Hashtable>::mapped_type& std::__detail::_Map_base<_Key, _Pair, std::_Select1st<_Pair>, true, _Hashtable>::operator[](const _Key&) [with _Key = Node, _Pair = std::pair<const Node, int>, _Hashtable = std::_Hashtable<Node, std::pair<const Node, int>, std::allocator<std::pair<const Node, int> >, std::_Select1st<std::pair<const Node, int> >, std::equal_to<Node>, std::hash<Node>, std::__detail::_Mod_range_hashing, std::__detail::_Default_ranged_hash, std::__detail::_Prime_rehash_policy, false, false, true>, std::__detail::_Map_base<_Key, _Pair, std::_Select1st<_Pair>, true, _Hashtable>::mapped_type = int]’
3sum.cpp:149:5:   instantiated from here
/usr/include/c++/4.6/bits/stl_function.h:209:23: error: passing ‘const Node’ as ‘this’ argument of ‘bool Node::operator==(Node)’ discards qualifiers [-fpermissive]
make: *** [threeSum] Error 1
Run Code Online (Sandbox Code Playgroud)

我想,我需要告诉C++如何散列类Node,但是,我不太清楚如何做到这一点.我该如何完成这项任务?

jog*_*pan 440

为了能够使用std::unordered_map(或其他一个无序的关联容器)与用户定义的键类型,您需要定义两件事:

  1. 一个哈希函数 ; 这必须是一个类,它会覆盖operator()并计算给定键类型对象的哈希值.一种特别直截了当的方法是专门std::hash为您的密钥类型模板.

  2. 平等比较函数 ; 这是必需的,因为哈希不能依赖于哈希函数将始终为每个不同的键提供唯一哈希值的事实(即,它需要能够处理冲突),因此它需要一种方法来比较两个给定的键完全匹配.您可以通过重载密钥类型(如您所做的那样)将其实现为覆盖的类operator(),或者作为特殊化的类std::equal,或者最简单的方法operator==().

散列函数的难点在于,如果您的密钥类型由多个成员组成,您通常会使用散列函数计算各个成员的散列值,然后以某种方式将它们组合成整个对象的一个​​散列值.为了获得良好的性能(即碰撞很少),您应该仔细考虑如何组合各个哈希值,以确保避免过于频繁地为不同的对象获取相同的输出.

散列函数的一个相当好的起点是使用位移和按位异或来组合各个散列值的起点.例如,假设键类型如下:

struct Key
{
  std::string first;
  std::string second;
  int         third;

  bool operator==(const Key &other) const
  { return (first == other.first
            && second == other.second
            && third == other.third);
  }
};
Run Code Online (Sandbox Code Playgroud)

这是一个简单的哈希函数(改编自cppreference示例中用于用户定义的哈希函数的哈希函数):

namespace std {

  template <>
  struct hash<Key>
  {
    std::size_t operator()(const Key& k) const
    {
      using std::size_t;
      using std::hash;
      using std::string;

      // Compute individual hash values for first,
      // second and third and combine them using XOR
      // and bit shifting:

      return ((hash<string>()(k.first)
               ^ (hash<string>()(k.second) << 1)) >> 1)
               ^ (hash<int>()(k.third) << 1);
    }
  };

}
Run Code Online (Sandbox Code Playgroud)

有了这个,你可以实例化一个std::unordered_map键类型:

int main()
{
  std::unordered_map<Key,std::string> m6 = {
    { {"John", "Doe", 12}, "example"},
    { {"Mary", "Sue", 21}, "another"}
  };
}
Run Code Online (Sandbox Code Playgroud)

它将自动使用std::hash<Key>上面定义的哈希值计算,并operator==定义Key为相等检查的成员函数.

如果您不想在std命名空间内专门化模板(尽管在这种情况下它是完全合法的),您可以将散列函数定义为单独的类并将其添加到映射的模板参数列表中:

struct KeyHasher
{
  std::size_t operator()(const Key& k) const
  {
    using std::size_t;
    using std::hash;
    using std::string;

    return ((hash<string>()(k.first)
             ^ (hash<string>()(k.second) << 1)) >> 1)
             ^ (hash<int>()(k.third) << 1);
  }
};

int main()
{
  std::unordered_map<Key,std::string,KeyHasher> m6 = {
    { {"John", "Doe", 12}, "example"},
    { {"Mary", "Sue", 21}, "another"}
  };
}
Run Code Online (Sandbox Code Playgroud)

如何定义更好的哈希函数?如上所述,定义良好的散列函数对于避免冲突并获得良好性能非常重要.对于一个真正的好的,您需要考虑所有字段的可能值的分布,并定义一个散列函数,该散列函数将该分布投影到尽可能宽且均匀分布的可能结果的空间.

这可能很困难; 上面的XOR /位移方法可能不是一个糟糕的开始.为了更好的开始,您可以使用Boost库中的hash_valuehash_combine函数模板.前者的行为方式与std::hash标准类型相似(最近还包括元组和其他有用的标准类型); 后者可以帮助您将各个哈希值合并为一个.这是重写使用Boost辅助函数的哈希函数:

#include <boost/functional/hash.hpp>

struct KeyHasher
{
  std::size_t operator()(const Key& k) const
  {
      using boost::hash_value;
      using boost::hash_combine;

      // Start with a hash value of 0    .
      std::size_t seed = 0;

      // Modify 'seed' by XORing and bit-shifting in
      // one member of 'Key' after the other:
      hash_combine(seed,hash_value(k.first));
      hash_combine(seed,hash_value(k.second));
      hash_combine(seed,hash_value(k.third));

      // Return the result.
      return seed;
  }
};
Run Code Online (Sandbox Code Playgroud)

这里是一个不使用boost的重写,但使用了很好的方法来组合哈希:

namespace std
{
    template <>
    struct hash<Key>
    {
        size_t operator()( const Key& k ) const
        {
            // Compute individual hash values for first, second and third
            // http://stackoverflow.com/a/1646913/126995
            size_t res = 17;
            res = res * 31 + hash<string>()( k.first );
            res = res * 31 + hash<string>()( k.second );
            res = res * 31 + hash<int>()( k.third );
            return res;
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

  • 如果你没有移位这两个字符串是相同的,那么xor会导致它们相互抵消.所以散列("a","a",1)与散列("b","b",1)相同.顺序也无关紧要,因此散列("a","b",1)与散列("b","a",1)相同. (39认同)
  • 你能否解释一下为什么有必要改变"KeyHasher"中的位? (10认同)
  • @Ben将它放入.h文件是正确的.`std :: hash`实际上不是struct*,而是struct*的*template(specialization).所以它不是一个实现 - 当编译器需要它时它将变成一个实现.模板应始终进入头文件.另见http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file (4认同)
  • @ nightfury`find()`返回一个迭代器,迭代器指向地图的"条目".一个条目是一个由键和值组成的`std :: pair`.因此,如果你执行`auto iter = m6.find({"John","Doe",12});`,你将得到`iter-> first`中的键和值(即字符串`"示例" "`)在`iter-> second`中.如果你想直接使用字符串,你可以使用`m6.at({"John","Doe",12})`(如果键不退出会抛出异常),或者`m6 [{" John","Doe",12}]`(如果密钥不存在,将创建一个空值). (3认同)

hon*_*onk 8

我认为,高戈潘(Jogojapan)给出了一个非常详尽的答复。您一定要在阅读我的文章之前先看一下。但是,我想添加以下内容:

  1. 您可以unordered_map单独定义比较函数,而不是使用相等比较运算符(operator==)。例如,如果您想使用后者将两个Node对象的所有成员彼此进行比较,而仅将某些特定成员用作的键,则这可能会有所帮助unordered_map
  2. 您也可以使用lambda表达式来代替定义哈希和比较函数。

总而言之,对于您的Node课程,代码可以编写如下:

using h = std::hash<int>;
auto hash = [](const Node& n){return ((17 * 31 + h()(n.a)) * 31 + h()(n.b)) * 31 + h()(n.c);};
auto equal = [](const Node& l, const Node& r){return l.a == r.a && l.b == r.b && l.c == r.c;};
std::unordered_map<Node, int, decltype(hash), decltype(equal)> m(8, hash, equal);
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 我只是在jogojapan回答的结尾重用了哈希方法,但是您可以在这里找到更通用的解决方案的想法(如果您不想使用Boost的话)。
  • 我的代码可能太小了。有关可读性更高的版本,请参见Ideone上的以下代码

  • 8 从哪里来,代表什么意思? (2认同)

cda*_*hms 5

使用自定义类作为键unordered_map(稀疏矩阵的基本实现)的最基本的可能复制/粘贴完整的可运行示例:

// UnorderedMapObjectAsKey.cpp

#include <iostream>
#include <vector>
#include <unordered_map>

struct Pos
{
  int row;
  int col;

  Pos() { }
  Pos(int row, int col)
  {
    this->row = row;
    this->col = col;
  }

  bool operator==(const Pos& otherPos) const
  {
    if (this->row == otherPos.row && this->col == otherPos.col) return true;
    else return false;
  }

  struct HashFunction
  {
    size_t operator()(const Pos& pos) const
    {
      size_t rowHash = std::hash<int>()(pos.row);
      size_t colHash = std::hash<int>()(pos.col) << 1;
      return rowHash ^ colHash;
    }
  };
};

int main(void)
{
  std::unordered_map<Pos, int, Pos::HashFunction> umap;

  // at row 1, col 2, set value to 5
  umap[Pos(1, 2)] = 5;

  // at row 3, col 4, set value to 10
  umap[Pos(3, 4)] = 10;

  // print the umap
  std::cout << "\n";
  for (auto& element : umap)
  {
    std::cout << "( " << element.first.row << ", " << element.first.col << " ) = " << element.second << "\n";
  }
  std::cout << "\n";

  return 0;
}
Run Code Online (Sandbox Code Playgroud)