如何在C ++中将std :: vector用作std :: unordered_map的键类型?

Mon*_*ans 3 c++ hash unordered-map vector

我正在尝试建立一个unordered map在n维空间中包含点的位置。我了解std::vector满足成为key的所有要求std::map,但是此代码无法编译。我收到一长串错误消息,但这似乎是最有问题的:

error: no match for call to ‘(const std::hash<std::vector<int> >) (const std::vector<int>&)'.

有谁知道为什么g ++似乎不认为它std::vector<int>是可哈希的?

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

using namespace std;

typedef vector<int> point;

int main()
{
    unordered_map<point, int>jugSpace;
    vector<int> origin(3, 0);

    jugSpace.insert( pair<point,int>(origin, 0) );
}
Run Code Online (Sandbox Code Playgroud)

Ser*_*eyA 5

无序映射要求密钥具有哈希功能。std::vector在标准实现中不存在此类功能。

但是,您可以使用std::map-它需要比较运算符,该运算符存在于vector中。

如果确实必须使用vector作为哈希映射的键(这似乎是可疑的),则应该自己实现哈希函数。


Dee*_*doo 5

您需要std::hash<>针对您的观点专门化模板类,例如:

namespace std {
  template<>
  class hash<point> {
  public:
    size_t operator()(const point &p) const {
      // put here your hash calculation code
    }  
  };
}
Run Code Online (Sandbox Code Playgroud)

或者创建自定义哈希器类并将其类型指定为模板成员std::unordered_map

class my_hash {
public:
  size_t operator()(const point &p) const {
    // your hash calculation code
  }
};

// somewhere in your code, where you declare your unordered_map variable
std::unordered_map<point, int, my_hash> myUnorderedMap;
Run Code Online (Sandbox Code Playgroud)

如果您想用作boost::hash_value哈希函数,则只需在哈希器实现中返回其结果,例如:

class my_hash {
public:
  size_t operator()(const point &p) const {
    return boost::hash_value(p);
  }
};
Run Code Online (Sandbox Code Playgroud)