我必须编写一个哈希函数,以便我可以放入std::pair<int,std::string>一个unordered_set.
关于输入:
使用字符串的哈希值(作为数字)是否有意义,并且只使用Cantor的对的枚举来生成"新"哈希?
由于"内置"哈希函数std::string应该是一个不错的哈希函数...
struct intStringHash{
public:
inline std::size_t operator()(const std::pair<int,std::string>&c)const{
int x = c.first;
std::string s = c.second;
std::hash<std::string> stringHash;
int y = stringHash(s);
return ((x+y)*(x+y+1)/2 + y); // Cantor's enumeration of pairs
}
};
Run Code Online (Sandbox Code Playgroud)
boost::hash_combine创建哈希是一种简单的方法:即使你不能使用Boost,这个函数也很简单,因此复制实现是微不足道的.
使用范例:
struct intStringHash
{
public:
std::size_t operator()(const std::pair<int, std::string>& c) const
{
std::size_t hash = 0;
hash_combine(hash, c.first);
hash_combine(hash, c.second);
return hash;
}
};
Run Code Online (Sandbox Code Playgroud)