如何在C++中实现 HashMap 时使用 std::function

How to use std::function when implementing a HashMap in C++

本文关键字:std function HashMap C++ 实现      更新时间:2023-10-16

我正在HashMap类声明中使用typedef std::function处理HashMap类。

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

对于类的私有成员,我有 HashFunction 哈希,可以与我自己的哈希函数一起使用,也可以使用提供给构造函数的其他函数。

HashFunction hash;
unsigned int myHashFunction(const std::string&) const;

默认构造函数必须将哈希设置为默认值,在我的例子中是 myHashFunction。以及一个构造函数,其中 HashFunction 作为参数必须使用该特定函数,而不是 myHashFunction。

HashMap::HashMap()
  : map(new Node*[INITIAL_BUCKET_COUNT]), mapSize(0), mapCapacity(INITIAL_BUCKET_COUNT),
  hash(std::bind(&HashMap::myHashFunction, this)) // This is definitely not correct
{
  initializeMap();
}
HashMap::HashMap(HashFunction hashFunction)
  : map(new Node*[INITIAL_BUCKET_COUNT]), mapSize(0),     mapCapacity(INITIAL_BUCKET_COUNT),
  hash(hashFunction) //Is this correct?
{
  initializeMap();
}

如何将 myHashFunction 或提供的哈希函数绑定到哈希,以便我可以在类成员函数中使用 hash(key) 来支持这两个哈希函数?如果我完全弄错了,请指导我走正确的道路。谢谢。

对于std::bind行,如果您尝试绑定成员函数,则需要包含一个占位符,如下所示:

std::bind(&HashMap::myHashFunction, this, std::placeholders::_1);

不过,您可能会发现最好将myHashFunction作为静态成员函数,除非它实际上使用HashMap中的其他成员或数据(我猜可能不应该)。

你为什么不使用std::hash?它在<functional>标头中定义。