为 unordered_map 定义自定义哈希函数和相等函数
我试图定义一种 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 不是有效的模板类型参数。该文档令人困惑,因为它没有确切说明模板参数应该是什么类型 - 我是否应该像我在这里那样给它函数,或者是否有其他类型的对象封装了该函数(因为文档确实谈到了“哈希函数对象类型”)?
I am trying to define a type of unordered_map that has a custom hash function and equality comparison function. The function prototypes of these functions are as follows:
//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
I have these function prototypes declared and then I try to declare the type as follows:
typedef std::tr1::unordered_map<set<Vertex3DXT*>, Cell3DXT*, VertexSetHashFunction, SetEqual> CellDatabaseMapType;
But it says that the VertexSetHashFunction and SetEqual are not valid template type arguments. The documentation is confusing because it doesn't say exactly what type the template arguments are supposed to be - am I just supposed to give it the function as I did here, or is there some other kind of object that encapsulates the function (because the documentation does talk about the "hash function object type")?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不幸的是,这些函数应该在类中声明为运算符 ()。像这样:
您不必将参数修改为 const 引用,但我强烈推荐它。制作 ::std::set 的副本相对昂贵,除非绝对必要,否则不应该这样做。
尾随 const 只是因为运算符实际上根本不修改类状态,主要是因为没有任何状态。这么明确地说出来真是太好了。
或者,您可以定义自己的 ::std::hash 模板专业化。如果您希望对特定集进行哈希处理,我实际上会推荐这种方法,因为如果您不向
unordered_map
或unordered_set
提供哈希函数,则默认使用此模板以及任何其他需要哈希函数的东西。Those functions should be declared as an operator () in a class, unfortunately. Like this:
You do not have to modify the arguments to be const references, but I would highly recommend it. Making a copy of a ::std::set is relatively expensive and you shouldn't do it unless you absolutely have to.
The trailing const is just because the operator doesn't actually modify the class state at all, mostly because there isn't any. It's just nice to say so explicitly.
Alternately, you could define your own specialization of the ::std::hash template. I would actually recommend this if there is one standard way you want that particular set hashed because this template is used by default if you do not supply a hash function to
unordered_map
orunordered_set
and anything else that needs a hash function.你需要函子。
You need functors.