2016-07-24 55 views
1

是否有使用std::unordered_set的類實現operator==hash的捷徑?具體來說,有沒有辦法(1)避免創建一個獨立的功能,和(2)避免定義整個類只是爲了保持size_t operator()(const Object& o) const {return o.hash();}直接使用成員函數unordered_set

當然,這些都不是問題,我只是好奇。

+0

當你說「類,它實現哈希」你的意思是作爲一個成員函數,還是一個免費函數? –

+0

會員功能。 – Zack

回答

2
  1. operator==被定義爲成員函數已被照顧。

  2. 如果類被用作鍵有一個成員函數hash() const然後我們可以做一些簡單的像這樣:

-

#include <unordered_map> 
#include <string> 

struct myclass { 
    std::size_t hash() const { return 0; } 
    bool operator==(const myclass& r) const { return true; } 
}; 

struct self_hash 
{ 
    template<class T> 
    auto operator()(const T& r) const { return r.hash(); } 
}; 

int main() 
{ 

    using mymap = std::unordered_map<myclass, std::string, self_hash>; 

    auto m = mymap(); 
}