我必须编写一个散列函数,这样我才能放置一个 std::pair<int,std::string>
在unordered_set
.
关于输入:
- 将被散列的字符串非常小(长度为 1-3 个字母)。
- 同样,整数将是较小的无符号数(远小于 unsigned int 的限制)。
使用字符串的散列(作为数字)并仅使用 Cantor 的对枚举来生成"new"散列是否有意义?
由于 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
}
};
最佳答案
boost::hash_combine
是一种创建哈希的简单方法:即使您不能使用 Boost,该函数也非常简单,因此它是 trivial to copy the implementation .
使用示例:
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;
}
};
关于c++ - 将字符串和整数散列在一起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39268446/