如何在c++中存储泛型元素数组

How to store an array of generic elements in C++?

本文关键字:泛型 元素 数组 存储 c++      更新时间:2023-10-16

我试图在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?

tablevoid**,所以table[idx]void*。您的解决方案应该像这样:

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