如何在C++中实现 HashMap 时使用 std::function
How to use std::function when implementing a HashMap in C++
我正在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>
标头中定义。
相关文章:
- Confusion: decltype vs std::function
- 为什么 std::function 可以作为 std::not2 的参数?
- 'max'匹配'std::function<const int &(const int &, const int &)>'无过载
- 传递给std::function template的template参数究竟代表什么
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- 将函数包装器转换为 std::function
- 类型擦除的std::function与虚拟函数调用的开销
- C++ std::function 对于类 exept 的所有实例都是空的(只有 Visual2019 编译器问题)
- 如果模板没有可变参数,则 Lambda 被推导出为 std::function
- 将 lambda 表达式传递给 std::function in C++
- 模板类的部分模板专用化,如 std::function
- 可变参数模板参数扩展 类型为 std::function 的类成员
- 从 std::function in C++ 访问模板化 lambda
- 什么是 std::function::argument_type 的替代品?
- C++派生类重载函数(带有 std::function 参数)不可见
- 如何在 qi 符号表中使用 std::function
- 将 std::function 与模板一起使用
- C++ 事件管理器的回调,使用 std::function 和 std:bind 以及派生类作为参数
- 我需要在 std::function 上使用 unique_ptr 吗?
- 如何将函数指针从 std::function 传递到 Linux 克隆?