Hash Function
hash函数定义方式
在容器中自定义 hash函数的方式
1.类中重载()运算符
2.直接定义函数
形式一
class ObjHash{
public:
std::size_t operator()(const Customer& c) const{
return ...
}
}
在构建STL的容器时,将该class的类型传入:
unordered_set<Customer,objHash> myset;
形式二
在构建时添加函数的类型,传入函数地址
size_t customer_hash_func(const Customer& c){
return ...
};
unordered_set<Customer,size_t(*)(const Customer&)> myset(20,customer_hash_func);
通用的一种hash函数设计
例子:
customer{
string fname;
int no;
string lname;
}
class CustomerHash{
size_t operator()(const Customer& c) const{
return hash_val(c.fname,c.lname,c.no);
}
}
template<typename... Types>
inline size_t hash_val(const Types&... args){
size_t seed = 0;
hash_val(seed,args...);
return seed;
}
template<typename T,typename... Types>
inline void hash_val(size_t &seed,const T&val, const Types&... args){
hash_combine(seed,val);
//递归调用,处理所有输入参数
hash_val(seed,args...);
}
template<typename T>
inline void hash_combine(size_t& seed,const T&val){
seed ^=std::hash<T>()(val)+0x9e3779b9+(seed<<6)+(seed>>2);
}
template<typename T>
inline void hash_val(size_t& seed,const T&val){
hash_combine(seed,val);
}