我正在尝试定义一种具有自定义哈希函数和相等比较函数的 unordered_map。这些函数的函数原型(prototype)如下:
//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
我声明了这些函数原型(prototype),然后尝试按如下方式声明类型:
typedef std::tr1::unordered_map<set<Vertex3DXT*>, Cell3DXT*, VertexSetHashFunction, SetEqual> CellDatabaseMapType;
但是它说 VertexSetHashFunction 和 SetEqual 不是有效的模板类型参数。该文档令人困惑,因为它没有确切说明模板参数应该是什么类型——我只是应该像我在这里做的那样给它函数,还是有一些其他类型的对象封装了函数(因为文档确实讨论了“哈希函数对象类型”)?
最佳答案
不幸的是,那些函数应该在类中声明为 operator ()。像这样:
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;
};
您不必将参数修改为常量引用,但我强烈推荐这样做。制作::std::set 的拷贝相对昂贵,除非绝对必要,否则不应该这样做。
尾随的 const 只是因为运算符实际上根本没有修改类状态,主要是因为根本没有。这么明确地说真好。
或者,您可以定义您自己的::std::hash 模板特化。如果您希望通过一种标准方法对特定集合进行哈希处理,我实际上会推荐此方法,因为如果您不向 unordered_map
或 unordered_set
提供哈希函数,默认情况下会使用此模板以及任何其他需要哈希函数的东西。
关于c++ - 为 unordered_map 定义自定义哈希函数和相等函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2099540/