【发布时间】:2017-01-09 03:44:42
【问题描述】:
我必须编写一个哈希函数,以便我可以将std::pair<int,std::string> 放在unordered_set 中。
关于输入:
- 将被散列的字符串非常小(长度为 1-3 个字母)。
- 同样,整数将是小的无符号数字(远小于无符号整数的限制)。
使用字符串的散列(作为数字)是否有意义,并且只使用康托尔的对枚举来生成“新”散列?
因为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,检查他们做了什么并复制代码 -
我无法使用 boost。你能解释一下怎么做吗?我已经阅读了另一篇关于创建函数 stackoverflow.com/questions/2590677/… 的帖子,但我不确定如何在上面的函数中使用它?