Ale*_*319 10 c++ templates 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
Run Code Online (Sandbox Code Playgroud)
我声明了这些函数原型,然后我尝试声明类型如下:
typedef std::tr1::unordered_map<set<Vertex3DXT*>, Cell3DXT*, VertexSetHashFunction, SetEqual> CellDatabaseMapType;
Run Code Online (Sandbox Code Playgroud)
但它表示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;
};
Run Code Online (Sandbox Code Playgroud)
您不必将参数修改为const引用,但我强烈推荐它.制作:: std :: set的副本相对昂贵,除非绝对必须,否则不应该这样做.
尾随const只是因为操作符实际上根本没有修改类状态,主要是因为没有.很明白地这么说.
或者,您可以定义自己的:: std :: hash模板的特化.如果有一种标准方式你希望特定的集合被散列,我实际上会推荐这个,因为如果你不提供散列函数unordered_map或者unordered_set需要散列函数的任何其他东西,默认情况下会使用这个模板.
You need functors.
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*/; }
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12364 次 |
| 最近记录: |