2016-07-24 57 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(); 
}