2015-10-10 37 views
0

我想構建一個固定大小的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 

我得到了很多取決於我嘗試不同的錯誤...

  1. error: request for member 'key' in '((HashTable*)this)->HashTable::table[idx]', which is of non-class type 'void*'

  2. 與第一個相同的錯誤。

  3. 這行只是給了我一整堵可怕的錯誤信息。

我不知道如何使我想要的工作。我應該做什麼類型的指針而不是void?

+0

爲什麼不讓你的HashTable模板? – marcinj

+1

你可以看看'boost :: any'。 – Jarod42

+0

看看[boost :: any](http://www.boost.org/doc/libs/1_58_0/doc/html/any.html) –

回答

2

tablevoid**,所以table[idx]void*。你的解決方案應該是這樣的:

((Node<T>*)table[idx])->key 
+0

謝謝,這正是它是什麼!它現在有效。我可以得到我想要的值: '((節點 *)表[idx]) - > key''' and '''*((Node *)table [idx ]) - > val''' – Grandclosing

相關問題