【问题标题】:Hashing a string and an int together?将字符串和 int 散列在一起?
【发布时间】:2017-01-09 03:44:42
【问题描述】:

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

关于输入:

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

使用字符串的散列(作为数字)是否有意义,并且只使用康托尔的对枚举来生成“新”散列?

因为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/… 的帖子,但我不确定如何在上面的函数中使用它?

标签: c++ c++11 hash


【解决方案1】:

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;
    }
};

【讨论】:

    【解决方案2】:

    是的,您将为具有哈希函数的每种类型生成哈希。

    将它们独占或散列组合起来是正常的:

    int hash1;
    int hash2;
    
    int combined = hash1 ^ hash2;
    

    【讨论】:

    • 你能解释一下为什么它是正常的吗?
    • 为了性能和简洁,通常使用这种方法来组合哈希。如果每个哈希函数都很好(低冲突率),那么使用 exclusive or 组合哈希的结果通常是好的(低冲突率)。毕竟它看起来不像你在做任何与安​​全相关的事情或创建一个最小的完美散列函数。
    猜你喜欢
    • 2011-02-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-21
    • 2012-07-07
    • 2011-09-30
    • 2020-03-17
    • 2015-12-14
    • 2013-11-24
    相关资源
    最近更新 更多