1
是否有使用std::unordered_set
的類實現operator==
和hash
的捷徑?具體來說,有沒有辦法(1)避免創建一個獨立的功能,和(2)避免定義整個類只是爲了保持size_t operator()(const Object& o) const {return o.hash();}
直接使用成員函數unordered_set
當然,這些都不是問題,我只是好奇。
是否有使用std::unordered_set
的類實現operator==
和hash
的捷徑?具體來說,有沒有辦法(1)避免創建一個獨立的功能,和(2)避免定義整個類只是爲了保持size_t operator()(const Object& o) const {return o.hash();}
直接使用成員函數unordered_set
當然,這些都不是問題,我只是好奇。
operator==
被定義爲成員函數已被照顧。
如果類被用作鍵有一個成員函數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();
}
當你說「類,它實現哈希」你的意思是作爲一個成員函數,還是一個免費函數? –
會員功能。 – Zack