为unordered_map定义自定义哈希函数和等式函数 [英] Defining custom hash function and equality function for unordered_map

查看:1435
本文介绍了为unordered_map定义自定义哈希函数和等式函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图定义一个具有自定义哈希函数和等式比较函数的unordered_map类型。这些函数的函数原型如下:

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

我有这些函数原型声明,然后尝试声明类型如下: / p>

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;

但它说VertexSetHashFunction和SetEqual不是有效的模板类型参数。文档是混乱的,因为它没有说明什么类型的模板参数应该是 - 我只是想给它的函数,我在这里,或有一些其他类型的对象封装的函数(因为)

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")?

推荐答案

这些函数应该声明为一个操作符类,不幸的是。像这样:

Those functions should be declared as an operator () in a class, unfortunately. Like this:

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 :: set的副本是相对昂贵的,你不应该这样做,除非你绝对必须。

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.

尾随const只是因为操作符实际上并不实际修改类的状态,主要是因为没有任何。

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.

或者,您可以定义自己的:: std :: hash模板的专业化。如果你没有提供一个散列函数到 unordered_map unordered_set 和任何需要散列函数的东西。

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 or unordered_set and anything else that needs a hash function.

这篇关于为unordered_map定义自定义哈希函数和等式函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆