c++ - 获取unordered_set哈希值并且它是否恒定

标签 c++ hash unordered-set

是否可以找出 unordered_set 中元素的哈希值(哈希键)?

例如;

unordered_set<string> errorStates;
errorStates.insert("File does not exist");

// Can I get the hash of this key?
int ERR_FILE_NOT_EXISTS = errorStates.keyHash("File does not exist");

此外,文件不存在的哈希值是否始终相同?如果我运行程序并在 errorStates 中插入 20 个值,以及当我运行程序并插入 200 个值时,哈希值会相同吗?这个想法是散列将是唯一的错误 ID 并将散列写入文件。

我正在创建一个 Status 类,以便轻松地从函数返回错误/成功结果,并从错误代码中获取错误消息 - 请参阅下面的部分实现。但也许有更好更合适的方法?

//usage
Status evtState = onMouseMove();
Status copyState = fileCopy();

class Status
{
public:
    static STATE registerState(const tstring &stateMsg)
    {
        states.emplace(stateMsg);
        return states.hashValue(stateMsg);
    }

    Status(const STATE &state) : state(state) {}
    ~Status() {}

    string toString() 
    {
        unordered_set<tstring>::const_iterator ele = states.find(state);

        return (ele != states.end()) ? *ele : "Undefined";
    }

    ostream& operator<<(Status& obj) 
    {
        return cout << obj.toString();
    }

private:
    static unordered_set<tstring> states;

    const STATE state;
};

最佳答案

可以从 std::unordered_set 检索哈希函数并用它来查找 key 的哈希值。

size_t h = myset.hash_function()("hello world");

Would the hash be the same if I run my program and insert 20 values into errorStates and when I run the program and insert 200?

std::unordered_set<T> 的默认哈希函数是 std::hash<T> 。此类模板的要求之一是:

The value returned shall depend only on the argument k for the duration of the program. [Note: Thus all evaluations of the expression h(k) with the same value for k yield the same result for a given execution of the program. —end note ]

hstd::hash<T>kT .

我对此的解释是,在程序的任何一次执行中,特定键的哈希值都是相同的。但是,在一系列运行中,表达式 h(k)不要求相同。

因此,插入的值的数量不会改变键的哈希值,仅在一次特定执行中改变。您不能假设某个键的哈希值在多次执行后保持不变。

关于c++ - 获取unordered_set哈希值并且它是否恒定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34247371/

相关文章:

c++ - '从 some_type** 到 const some_type** 的无效转换'

c++ - WINAPI RegisterApplicationRestart 不清除打开的套接字

c++ - if-else if 梯形图和编译器优化

在C中计算结构的哈希值

PHP.net 说 md5() 和 sha1() 不适合作为密码?

c++ - 赋值运算符与自定义构造函数的关系

algorithm - Aix:如何在AIX/etc/security/passwd上生成有效的sha1/sha256/sha512密码哈希?

c++ - unordered_set 通过地址传递

c++ - 如何在迭代时有效地替换 unordered_set 中的元素?

c++ - 如何填充项目为 8 个字符的集合? (std::set<字符[8]>)