在编程的过程中,hash_set和hash_map的key有时候可能需要是一些复杂的元素,如数对,结构体或者某一个类,这时候可能需要自己重新写一个hash函数来使得hash_set和hash_map能够正常使用。hash_set和hash_map的结构如下,只需要重载除key和value的下一个参数即可。
template<class Key,
class Ty,
class Hash = std::hash<Key>,
class Pred = std::equal_to<Key>,
class Alloc = std::allocator<std::pair<const Key, Ty> > >
class unordered_map;
> class unordered_map
template<class value,
class Hash = std::hash<value>,
class Pred = std::equal_to<value>,
class Alloc = std::alloc>
class unordered_set;
重写hashfun结构体的内容如下:要注意hash<int>()(a.first)这个格式。
struct hashfun{
size_t operator()(const pair<int,int>& a)const
{
return hash<int>()(a.first)*10+hash<int>()(a.second);
}
};
unordered_set<pair<int,int>,hashfun> check;