【发布时间】:2016-02-25 00:20:44
【问题描述】:
我正在尝试为 hash map 编写一个实现,除了 iostream、string 和 cassert 之外,我不能使用 stdlib 中的任何东西。
它需要是通用的,因此填充存储桶的值可以是任何类型。我需要为此模板,但无法以任何方式传递散列函数。这将是头文件:
template<typename Value, typename hashFunction>
class hashTable{
public:
hashTable(int size){
//Creates an empty vector of size on the table
}
define(Value v){
loads value in Vector[hashFunction(v)];
}
...
private:
Vector with all the elements
}
注意:我想我不需要密钥模板,是吗?
我无法在我的类中定义散列函数,因为我必须创建一个适用于所有类型(字符串到 int、int 到 int、double 到 int 等)的哈希函数。所以我想唯一的解决方案是将函数作为参数传递给我的 main.这将是主要的。
int hashF(int v){return v}
int main(){
hashTable<int,int,hashF> table(5);
}
但这不起作用,g++ 告诉我“预期类型但得到了 hashF”。我想我可以传递一个指向函数的指针,但这似乎是一种 hack 而不是真正的解决方案。有没有更好的办法?
【问题讨论】:
-
我从来没有弄清楚为什么你不能将一个简单的函数作为常规模板参数传递。如果你将它包装在一个结构中为
operator()你的代码仍然可以工作。 -
我试试,谢谢!
标签: c++ templates hashmap parameter-passing hashtable