c++ - 将字符串和整数散列在一起?

标签 c++ c++11 hash

我必须编写一个散列函数,这样我才能放置一个 std::pair<int,std::string>unordered_set .

关于输入:

  1. 将被散列的字符串非常小(长度为 1-3 个字母)。
  2. 同样,整数将是较小的无符号数(远小于 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/

相关文章:

c++ - 如何在模板函数中为整数类型选择snprinf掩码?

ruby - 如何使用ruby更改小写的哈希键

Perl - 如何将哈希转换为查询字符串?

C++ 编译大型结构时内存使用过多

c++ - boost::fusion 的目的是什么?

c++ - 如何解决 'vector subscript out of range' 错误?

php - 哈希等于的行为不正常

c++ - 异常传播和 std::future

c++ - 如何创建一个编译时静态类类型来初始化具有特定值的成员容器?

c++ - 引用返回和右值