繁体   English   中英

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

[英]How to use std::vector as the type of key for an std::unordered_map in C++?

我正在尝试构建一个unordered map来包含n维空间中的点。 我理解std::vector满足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) );
}

无序映射需要密钥的哈希函数的可用性。 标准实现中std::vector不存在这样的函数。

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

如果你真的必须使用vector作为哈希映射的关键(这看起来很可疑),你应该自己实现哈希函数。

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

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

或者创建自定义hasher类并将其类型指定为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;

如果你想使用boost::hash_value作为哈希函数,那么只需在你的哈希实现中返回它的结果,例如:

class my_hash {
public:
  size_t operator()(const point &p) const {
    return boost::hash_value(p);
  }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM