我有几个 GUID,我想实现一个哈希表来快速检索它们。我该怎么做?
如果我将 GUID 视为哈希代码,我需要执行类似的操作
index = GUID % prime_number_that_covers_all_GUID_bits
但我不确定这是否是正确的方法。我应该如何实现这样的哈希表?
最佳答案
您可以使用std::unordered_map
,需要 Key
在您的情况下输入( GUID
),然后输入 Value
类型,可能是一些用户信息或程序信息(取决于您的应用程序)。存储就像调用成员函数 insert()
一样简单或emplace()
并通过调用find()
来查找存储的值。 .
下面的示例使用 std::string
作为 key 的基础类型,并且隐式 std::hash<std::string>
作为哈希函数。对于其他 GUID 类型,您可能需要滚动自己的哈希函数对象并将其作为模板参数传递给哈希表。
#include <iostream>
#include <ios>
#include <string>
#include <unordered_map>
typedef std::string GUID;
class UserInfo
{
public:
UserInfo(bool b): is_genius_(b) {}
bool is_genius() const { return is_genius_; }
private:
bool is_genius_;
// your stuff here
};
int main()
{
std::unordered_map<GUID, UserInfo> table;
GUID x = "Johnny Pauling";
// insert into table
table.emplace(x, UserInfo(true));
// lookup in table
auto it = table.find(x);
// if found, print it
if (it != table.end())
std::cout << std::boolalpha << it->second.is_genius();
}
LiveWorkSpace 上的输出
关于c++ - GUID 和哈希表 - 如何使用它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14438621/