定义自定义哈希函数和平等功能unordered_map
-
21-09-2019 - |
题
我试图定义类型unordered_map的具有自定义的散列函数和相等比较功能。是这些函数的函数原型如下:
//set<Vertex3DXT*> is the type of the key; Cell3DXT* is the type of the value
size_t VertexSetHashFunction(set<Vertex3DXT*> vertexSet); //hash function
bool SetEqual(set<Vertex3DXT*> a, set<Vertex3DXT*> b); //equality
我有这些函数原型声明,然后我试图声明类型,如下所示:
typedef std::tr1::unordered_map<set<Vertex3DXT*>, Cell3DXT*, VertexSetHashFunction, SetEqual> CellDatabaseMapType;
但它说,VertexSetHashFunction和SetEqual不是有效的模板类型参数。该文档混乱,因为它并没有说什么类型的模板参数都应该是 - 我只是应该给它的功能我在这里做,或者是有一些其他类型的对象,它封装了功能(因为文档中则有关“散列函数对象类型”)通话?
解决方案
这些功能应被声明为在一个类的操作者(),不幸的是。像这样:
class VertexSetHashFunction {
public:
::std::size_t operator ()(const ::std::set<Vertex3DXT*> &vertexSet) const;
};
class SetEqual {
public:
bool operator ()(const ::std::set<Vertex3DXT*> &a, const ::std::set<Vertex3DXT*> &b) const;
};
您不必修改参数为const引用,但我会极力推荐它。制作::的std ::集的副本是比较昂贵的,你不应该这样做,除非你绝对必须的。
在尾随常量仅仅是因为运营商实际上并没有修改类的状态可言,主要是因为没有任何。这只是漂亮这么明确地说。
另外,还可以定义自己的::性病::哈希模板的专业化。我真的建议这如果你想散列特定的,因为此模板默认使用的,如果你不提供散列函数unordered_map
或unordered_set
和其他任何需要的哈希函数。
其他提示
您需要函子。
struct VertexSetHashFunction {
size_t operator() (const set<Vertex3DXT*>& vertexSet) const { return /*whatever*/; }
};
struct SetEqual {
bool operator() (const set<Vertex3DXT*>& a, const set<Vertex3DXT*>& b) const { return /*whatever*/; }
};
不隶属于 StackOverflow