1.基本数据类型,string等使用unordered map可以直接使用,如hash<int>()(x)。
结构体使用unordered map需要一个hash函数和一个equal函数。
2.
hash函数一般用函数对象实现。(注意:返回值size_t)
equal函数可以用函数对象,也可以直接重载==运算符。
struct point{
int x,y;
}p;
unordered_map<point,vector<int>,pointHash ,pointEqual> mp;//equal用函数对象
unordered_map<point,vector<int>,pointHash> mp;//equal重载==
a.hash函数
比较朴素的方法就是直接相加。
struct pointHash{
size_t operator () (const point &p) const{
return hash<int>()(p.x) + hash<int>() (p.y);
}
};
复杂一点就是。。
template<typename T>
inline void hash_combine(std::size_t& seed, const T& val)
{
seed ^= std::hash<T>()(val)+0x9e3779b9 + (seed << 6) + (seed >> 2);
}
template<typename T>
inline void hash_val(std::size_t& seed, const T& val)
{
hash_combine(seed, val);
}
template<typename T, typename... Types>
inline void hash_val(std::size_t& seed, const T& val, const Types&... args)
{
hash_combine(seed, val);
hash_val(seed, args...);
}
template<typename... Types>
inline std::size_t hash_val(const Types& ...args)
{
std::size_t seed = 0;
hash_val(seed, args...);
return seed;
}
struct pointHash{
size_t operator () (const point &p) const{
return hash_val(p.x,p.y);
}
};
b.equal函数
重载==运算符
struct point{
int x,y;
bool operator == (const point &b) const{
return x == b.x && y == b.y;
}
}p;
对象函数
struct pointEqual{
bool operator () (const point &a,const point &b) const{
return a.x == b.x && a.y == b.y;
}
};

2872

被折叠的 条评论
为什么被折叠?



