gpt4 book ai didi

c++ - 在 C++ 中将 typedef 函数从头文件实现到源文件中

转载 作者:行者123 更新时间:2023-11-30 02:42:36 25 4
gpt4 key购买 nike

我目前正在尝试为 HashMap 类实现哈希函数。我们得到了一个 HashMap.h 文件,我们不能更改任何预定义的成员变量和函数。在为 HashMap 类实现我的 .cpp 文件时,这并没有被证明是一个挑战,直到我到达这一行:

typedef std::function<unsigned int(const std::string&)> HashFunction;

通常如果这是在我的头文件中:

HashMap();

我可以在我的源文件中这样做来实现它:

HashMap::HashMap() {
// code here
}

我的问题是如何在我的源文件中实现这个 typedef?我有一个哈希函数 (hashFunc),它接受一个 const 字符串,并返回一个无符号整数,如下所示:

HashMap::hashFunc(const std::string& key)
{
unsigned int hashValue = 0; // what we end up returning
// hashFunc code here
return hashValue;
}

但是由于我必须在我的源文件中的构造函数、复制器等中使用这个散列函数,所以我应该从这个 typedef 中声明它。例如,像:

HashMap::HashMap(HashFunction hashFunc) { }

我怎样才能使这项工作?我尝试过 HashFunction HashMap::hashFunc()、HashMap::HashFunction hashFunc() 和 HashMap::HashFunction::hashFunc() 之类的方法,但没有任何效果:( 我是 C++ 的新手,所以我意识到我可能看起来现在对这个问题很愚蠢,但我不知道如何继续。

最佳答案

您可能已经意识到,std::function<unsigned int(const std::string&)>是一种接受字符串输入并返回 unsigned int 的函数类型, 用作 map 的哈希函数。

那个typedef允许您识别“接受字符串并返回无符号的任何函数”。此时,HashFunction只是一种类型,例如 intstring是。

HashMap 的构造函数可以有一个 HashFunction 类型的参数指定哈希函数,例如:

class HashMap {
public:
explicit HashMap(const HashFunction &h): hash(h) {}
//...
void put(std::string element) {
unsigned int h = hash(element);
//...
}
//...
private:
HashFunction hash;
}

如你所见,我声明了一个变量 hash , 类型 HashFunction 您可以在 HashMap::put 中调用的函数方法。

此时您可能想知道如何创建类型为 HashFunction 的东西.好吧,最简单的答案是:通过定义一个“标准”函数,其签名与 HashFunction 中的一个相匹配。 .例如,这是一个 DJB 哈希:

unsigned int DJB_hash(const std::string &s) {
unsigned int h = 5318;

for (char c: s) {
h = 33 * h + c;
}

return h;
}

或者,在 C++11 之前:

unsigned int DJB_hash(const std::string &s) {
unsigned int h = 5318;

for (int i = 0; i < s.size(); ++i) {
h = 33 * h + s[i];
}

return h;
}

现在您可以使用以下方法构建 HashMap :

HashMap map(DJB_hash);

关于c++ - 在 C++ 中将 typedef 函数从头文件实现到源文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26946453/

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