我正在创建一个哈希表。理想情况下,键应该是int类型,并且值可以是任何类型(int,char,double,string等)。这是我的入口和表类:
#include<iostream>
using namespace std;
template<typename P>
class HashEntry {
private:
int key;
P value;
public:
HashEntry(int key, P value) {
this->key = key;
this->value = value;
}
int getKey() {
return key;
}
P getValue() {
return value;
}
};
const int TABLE_SIZE = 128;
template<typename P>
class HashMap {
private:
HashEntry<P>**table;
public:
HashMap() {
table = new HashEntry<P>*[TABLE_SIZE];
for (int i = 0; i < TABLE_SIZE; i++)
table[i] = NULL;
}
P get(int key) {
int hash = (key % TABLE_SIZE);
while (table[hash] != NULL && table[hash]->getKey() != key)
hash = (hash + 1) % TABLE_SIZE;
if (table[hash] == NULL)
return -1;
else
return table[hash]->getValue();
}
void put(int key, P value) {
int hash = (key % TABLE_SIZE);
while (table[hash] != NULL && table[hash]->getKey() != key)
hash = (hash + 1) % TABLE_SIZE;
if (table[hash] != NULL)
delete table[hash];
table[hash] = new HashEntry<P>(key, value);
}
~HashMap() {
for (int i = 0; i < TABLE_SIZE; i++)
if (table[i] != NULL)
delete table[i];
delete[] table;
}
};
int main()
{
HashMap<char>* h1 = new HashMap<char>();
h1->put(5, 15);
cout << h1->get(5) << endl;
return 0;
}
问题是,当我尝试添加模板类型名称P等模板时,我想在两个类中用int
替换变量value
的每个P
实例。另外,我怎样才能在main中分配这个?上面的代码没有编译时错误,但是在检索值时我什么都没得到。