在结构体中的TR1 unordered_map中定义一个散列函数 [英] Defining a hash function in TR1 unordered_map inside a struct
问题描述
根据此< a>,可以在TR1 unordered_map中定义一个等式函数,如下所示:
According to this, it is possible to define an equality function in a TR1 unordered_map like this:
#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;
是否可以以同样的方式定义散列函数?
Is it possible to define the hash function the same way?
推荐答案
如果你想改变默认的哈希值(或者更频繁地为当前不支持的类型提供哈希),你提供一个< c $ c> std :: tr1 :: hash< T> 为您的键类型:
If you want to change the default hashing (or, more often, provide hashing for a type that isn't currently supported), you provide a specialization of std::tr1::hash<T>
for your key-type:
namespace std {
namespace tr1 {
template<>
struct hash<typename my_key_type> {
std::size_t operator()(my_key_type const &key) {
return whatever;
}
};
}
}
请注意,将现有模板专用于用户定义类型是罕见案例之一,您可以在命名空间std
中具体允许编写代码。
Note that specializing an existing template for a user-defined type is one of the rare cases where you specifically are allowed to write code in namespace std
.
这篇关于在结构体中的TR1 unordered_map中定义一个散列函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!