C++ c++;重写模板类中的默认函数
作为一个学习练习,我想创建自己的哈希表类(是的,我知道std::unordered_映射和std::unordered set)。所以,我写了这段代码:C++ c++;重写模板类中的默认函数,c++,function,templates,C++,Function,Templates,作为一个学习练习,我想创建自己的哈希表类(是的,我知道std::unordered_映射和std::unordered set)。所以,我写了这段代码: using std::cout; using std::endl; using std::vector; using std::unique_ptr; template <class K, class V, class U=std::hash<K>> class hashTable { int order=0;
using std::cout;
using std::endl;
using std::vector;
using std::unique_ptr;
template <class K, class V, class U=std::hash<K>>
class hashTable
{
int order=0;
vector<myNode<K, V>> nodes;
public:
hashTable(U u = U()){}; // : hashPtr(u)
size_t gethash(K key, int level=0, const U & u=U());
};
template<class K, class V, class U>
size_t hashTable<K, V, U>::gethash(K key, int level, const U & u)
{
return u(key) % divisors[level];
}
使用std::cout;
使用std::endl;
使用std::vector;
使用std::unique\u ptr;
模板
类哈希表
{
整数阶=0;
向量节点;
公众:
哈希表(U=U()){};//:hashPtr(U)
size_t gethash(K键,int-level=0,常量U&U=U());
};
模板
大小\U t哈希表::gethash(K键,int级别,常量U&U)
{
返回u(键)%除数[级别];
}
它编译得很好,基本上达到了我的预期:
hashTable<int,int> hast;
for(int i=0;i<40;++i)
cout << "hash of "<<i<<" is " << hast.gethash(i, 2) << endl;
哈希表hast;
对于(int i=0;i您可以打开std
命名空间,并将节点类型的hash
模板专门化为:
namespace std {
template<>
struct hash<myNode<int, int>>
{
std::size_t operator()(myNode<int, int> const& node) const {
int i = node.getkey();
int j = node.getvalue();
std::hash<int> hash_fn;
return hash_fn(i)+hash_fn(j);
}
};
}
名称空间std{
模板
结构散列
{
std::size\u t运算符()(myNode常量和node)常量{
int i=node.getkey();
int j=node.getvalue();
std::hash散列\u fn;
返回散列fn(i)+散列fn(j);
}
};
}
然后创建一个表,如下所示:
hashTable < myNode<int, int>, int> hashMyNode;
hashTablehashMyNode;
现在,您不必使用函数作为散列,而是可以将节点的散列创建为std::hash_fn{}
,但不必显式创建它们,因为您已经将其类型提供为默认参数(第三个参数)在hashTable的
myNode
,除数
?nodeHash
不是一个类型,而是一个函数,不能像那样将其用作模板参数。hashTable
和提供nodeHash
之后到gethash
是一种可能性。或者创建一个函子。除数是一个接近2^n的素数表。因此,我添加了以下内容:hashTablehashMyNode;hashMyNode.gethash(node,2,nodeHash)
我有一大堆错误,我无法在5分钟的时间限制内找到这个评论编辑器。谢谢@Jarod42。我对这些评论无能为力。
auto node = myNode<int, int>(1, 3);
hashTable < myNode<int, int>, int, size_t (*)(myNode<int,int> node)> hashMyNode;
hashMyNode.gethash(node, 2, nodeHash);
Severity Code Description Project File Line Suppression State
Error (active) E1776 function "myNode<K, V>::myNode(const myNode<int, int> &) [with K=int, V=int]" (declared implicitly) cannot be referenced -- it is a deleted function somePrime E:\source\repos\somePrime\somePrime.cpp 139
Severity Code Description Project File Line Suppression State
Error C2280 'myNode<int,int>::myNode(const myNode<int,int> &)': attempting to reference a deleted function somePrime e:\source\repos\someprime\someprime.cpp 139
namespace std {
template<>
struct hash<myNode<int, int>>
{
std::size_t operator()(myNode<int, int> const& node) const {
int i = node.getkey();
int j = node.getvalue();
std::hash<int> hash_fn;
return hash_fn(i)+hash_fn(j);
}
};
}
hashTable < myNode<int, int>, int> hashMyNode;