是否可以找出 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 ]
与 h
是 std::hash<T>
和k
是 T
.
我对此的解释是,在程序的任何一次执行中,特定键的哈希值都是相同的。但是,在一系列运行中,表达式 h(k)
不要求相同。
因此,插入的值的数量不会改变键的哈希值,但仅在一次特定执行中改变。您不能假设某个键的哈希值在多次执行后保持不变。
关于c++ - 获取unordered_set哈希值并且它是否恒定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34247371/