簡體   English   中英

為unordered_map定義自定義散列函數和相等函數

[英]Defining custom hash function and equality function for 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不是有效的模板類型參數。 文檔很混亂,因為它沒有准確說明模板參數應該是什么類型 - 我只是應該給它像我在這里做的那樣,或者是否有一些其他類型的對象封裝了函數(因為文檔確實談到“哈希函數對象類型”)?

不幸的是,這些函數應該在類中聲明為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;
};

您不必將參數修改為const引用,但我強烈推薦它。 制作:: std :: set的副本相對昂貴,除非絕對必須,否則不應該這樣做。

尾隨const只是因為操作符實際上根本沒有修改類狀態,主要是因為沒有。 很明白地這么說。

或者,您可以定義自己的:: std :: hash模板的特化。 如果有一種標准方式你希望特定的集合被散列,我實際上會推薦這個,因為如果你沒有為unordered_mapunordered_set提供散列函數以及需要散列函數的任何其他東西,則默認使用此模板。

你需要仿函數。

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*/; }
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM