[英]Defining a hash function in TR1 unordered_map inside a struct
根據這個 ,可以在TR1 unordered_map中定義一個相等函數,如下所示:
#include <tr1/unordered_map>
using namespace std;
using namespace std::tr1;
struct foo{
...
bool operator==(const foo& b) const{
return ..;
}
};
unordered_map<foo,int> map;
是否可以以相同的方式定義散列函數?
如果要更改默認哈希(或者更常見的是,為當前不支持的類型提供哈希),則為鍵類型提供std::tr1::hash<T>
的特化:
namespace std {
namespace tr1 {
template<>
struct hash<typename my_key_type> {
std::size_t operator()(my_key_type const &key) {
return whatever;
}
};
}
}
需要注意的是,專門為用戶定義類型的現有模板,在那里你特別允許在編寫代碼的極少數情況下一個namespace std
。
unordered_map類的簽名是這樣的:
template<class Key,
class Ty,
class Hash = std::hash<Key>,
class Pred = std::equal_to<Key>,
class Alloc = std::allocator<std::pair<const Key, Ty> > >
class unordered_map;
您的示例有效,因為默認的Pred,std :: equal_to <>默認情況下使用operator ==檢查相等性。 編譯器找到你的foo :: operator == member函數並使用它。
std :: hash沒有任何可以在你的類上調用成員函數的特化,所以你不能只使用自定義哈希向foo添加成員。 您將需要專門化std :: hash。 如果你想在foo上調用成員函數,請繼續。 你最終會得到這樣的東西:
struct foo
{
size_t hash() const
{
// hashing method here, return a size_t
}
};
namespace std
{
// Specialise std::hash for foo.
template<>
class hash< foo >
: public unary_function< foo, size_t >
{
public:
size_t operator()( const foo& f )
{
return f.hash();
}
};
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.