一起散列字符串和int?

Kai*_*zay 2 c++ hash c++11

我必须编写一个哈希函数,以便我可以放入std::pair<int,std::string>一个unordered_set.

关于输入:

  1. 将要散列的字符串非常小(长度为1-3个字母).
  2. 同样,整数将是无符号数,它们很小(远小于unsigned int的限制).

使用字符串的哈希值(作为数字)是否有意义,并且只使用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)

mil*_*bug 5

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)