gpt4 book ai didi

c++ - 获取unordered_set hash值,是否常量

转载 作者:行者123 更新时间:2023-11-30 02:34:53 26 4
gpt4 key购买 nike

是否可以找出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");

File does not exist 的散列值是否始终相同?如果我运行我的程序并将 20 个值插入 errorStates 并且当我运行该程序并插入 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 中检索哈希函数并使用它来查找键的散列值。

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 ]

h作为std::hash<T>k作为T .

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

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

关于c++ - 获取unordered_set hash值,是否常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34247371/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com