[英]How to use std::vector as the type of key for an std::unordered_map in C++?
I'm trying to build an unordered map
to contain points in n-dimensional space. 我正在尝试构建一个
unordered map
来包含n维空间中的点。 I understand that std::vector
meets all the requirements for being a key in std::map
, and yet this code does not compile. 我理解
std::vector
满足std::map
作为键的所有要求,但是这段代码不能编译。 I get a long list of error messages, but this seems the most problematic: 我得到一长串错误消息,但这似乎是最成问题的:
error: no match for call to '(const std::hash<std::vector<int> >) (const std::vector<int>&)'.
Does anyone have any idea as to why g++ doesn't seem to think that std::vector<int>
is hashable? 有没有人知道为什么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) );
}
Unordered map requires availability of hash function for the key. 无序映射需要密钥的哈希函数的可用性。 Such function does not exist for
std::vector
in standard implementation. 标准实现中
std::vector
不存在这样的函数。
You could use std::map
, though - it requires comparison operator, which exists for vector. 你可以使用
std::map
- 它需要比较运算符,它存在于vector中。
If you really must use vector as a key to hash map (which seems dubious), you should implement hashing function yourself. 如果你真的必须使用vector作为哈希映射的关键(这看起来很可疑),你应该自己实现哈希函数。
You need to specialize template class std::hash<>
for your point like: 您需要为您的点专门化模板类
std::hash<>
,例如:
namespace std {
template<>
class hash<point> {
public:
size_t operator()(const point &p) const {
// put here your hash calculation code
}
};
}
Or create custom hasher class and specify its type as template member for std::unordered_map
: 或者创建自定义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;
If you want to use boost::hash_value
as hash function then just return its result in your hasher implementation, ex: 如果你想使用
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.