c++ - 为 unordered_map 定义自定义哈希函数和相等函数

标签 c++ templates unordered-map

我正在尝试定义一种具有自定义哈希函数和相等比较函数的 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_mapunordered_set 提供哈希函数,默认情况下会使用此模板以及任何其他需要哈希函数的东西。

关于c++ - 为 unordered_map 定义自定义哈希函数和相等函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2099540/

相关文章:

c++ - 编译后停止和仅检查语法之间的区别

c++ - 仅当从 C++11 中的 B 派生时,如何有条件地调用 B::f?

c++ - 将 unordered_map 设置为 unordered_map 的值

c++ - unordered_map 判断key是否在map中

c++ - Physx 3 的几个新手问题

c++ - 带cmake的 Armadillo 链接器错误

.net - 为客户提供 .NET 的替代方案

c++ - 侵入式、循环式、无分支式、双向链表——如何让链表识别节点成员字段?

c++ - 使用 SFINAE 解决过载歧义

c++ - find 函数在 unordered_map 中的工作原理是搜索键值