在结构内部的TR1 unordered_map中定义哈希函数

Ale*_*ros 4 c++ hash unordered-map tr1

根据这个,可以在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;
Run Code Online (Sandbox Code Playgroud)

是否可以以相同的方式定义散列函数?

Jer*_*fin 12

如果要更改默认散列(或者更常见的是,为当前不支持的类型提供散列),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;
        }
    };
}
}
Run Code Online (Sandbox Code Playgroud)

需要注意的是,专门为用户定义类型的现有模板的一个罕见的,你具体的情况允许在编写代码namespace std.