根据 this ,可以像这样在 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>
的特化对于您的 key 类型:
namespace std {
namespace tr1 {
template<>
struct hash<typename my_key_type> {
std::size_t operator()(my_key_type const &key) {
return whatever;
}
};
}
}
请注意,为用户定义的类型专门化现有模板是罕见情况之一,您特别允许在 namespace std
中编写代码.
关于c++ - 在结构内部的 TR1 unordered_map 中定义哈希函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5434484/