作为一个学习练习,我想创建自己的Hash Table类(是的,我知道std :: unordered_map和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;
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];
}
并且它编译得很好,并且在主要的时候做我所期望的:
hashTable<int,int> hast;
for(int i=0;i<40;++i)
cout << "hash of "<<i<<" is " << hast.gethash(i, 2) << endl;
但是,当我编写以下函数时:
size_t nodeHash(myNode<int,int> node) {
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, nodeHash> hashMyNode;
我收到编译错误:函数“nodeHash”不是类型名称。
我知道我不知道我在做什么,因为这些模板化的功能对我来说是新的。我似乎知道这很“危险”。但是,如果有人能够朝着正确的方向推动我,或者给我一个完整的解决方案,将一个外部函数包含在一个类中(比如std :: unordered_map或std :: sort do),我当然会很感激。
编辑:
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
这指的是节点变量。
您可以打开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);
}
};
}
然后创建一个表格:
hashTable < myNode<int, int>, int> hashMyNode;
现在不是使用函数作为哈希,而是可以为std::hash<myNode<int,int>> hash_fn{}
创建节点的哈希,但是你不必显式创建它们,因为你已经提供了类型作为hashTable
的默认参数(第3个参数)