我想構建一個固定大小的C++散列表;該表應該能夠獲取任何類型的數據,所以我使用模板來完成此操作。我試圖使用一個void指針數組來保存我的鏈表,但我的工作難度非常大。如何在C++中存儲通用元素數組?
節點結構:
template <typename T>
struct Node {
std::string key;
T val;
Node<T> next;
}
類:
class HashTable {
private:
int size;
int elements;
void **table;
public:
HashTable(int size) {
this->size = size;
elements = 0;
table = new void*[size];
//initialize table
for(int i = 0; i < size; i++) {
table[i] = NULL;
}
}
~HashTable() {
delete [] table;
}
template <typename T>
bool set(string key, T val) {
std::tr1::hash<std::string> hash_function;
std::size_t hash_value = hash_function(key);
int idx = hash_value % size;
if(table[idx] == NULL) {
//newly created bucket, increment elements variable to signify bucket use
elements++;
Node<T> node;
node.key = key;
node.val = val;
node.next = NULL;
table[idx] = &node;
cout << "Node: " << node.key << ", " << *node.val << endl;
//first error
cout << "Table: " << table[idx].key << endl;
//second error
cout << "Table: " << (Node<T>)table[idx].key << endl;
//third error
cout << "Table: " << static_cast<Node<T>>(table[idx]).key << endl;
} else {
}
}
//other methods
我得到了很多取決於我嘗試不同的錯誤...
error: request for member 'key' in '((HashTable*)this)->HashTable::table[idx]', which is of non-class type 'void*'
與第一個相同的錯誤。
這行只是給了我一整堵可怕的錯誤信息。
我不知道如何使我想要的工作。我應該做什麼類型的指針而不是void?
爲什麼不讓你的HashTable模板? – marcinj
你可以看看'boost :: any'。 – Jarod42
看看[boost :: any](http://www.boost.org/doc/libs/1_58_0/doc/html/any.html) –