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

标签 c++ hashtable void

我正在尝试用 C++ 构建一个固定大小的哈希表;该表应该能够获取任何类型的数据,因此我使用模板来完成此操作。我正在尝试使用 void 指针数组来保存我的链接列表,但我很难让它工作。

节点结构:

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. 错误:请求'((HashTable*)this)->HashTable::table[idx]'中的成员'key',它是非类类型'void*'

  2. 与第一个错误相同。

  3. 这一行给我一大堆可怕的错误消息。

我现在不知道如何让我想要的东西发挥作用。我应该制作什么类型的指针而不是 void?

最佳答案

table 是一个 void**,所以 table[idx] 是一个 void*。你的解决方案应该是这样的:

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

关于c++ - 如何在 C++ 中存储泛型元素数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33057492/

相关文章:

c# - 如何从另一个窗体调用函数

c++ - C++ 中的开关只能有一个默认值吗?

c++ - 检查正确的输入会导致无限循环

c++ - 如何让 clang 3.4 编译通用 lambdas?

c++ - Count.h :10:5: error: ISO C++ forbids declaration of 'T' with no type [-fpermissive] T(); ^

.net - 使用带有字符串键和不区分大小写的搜索的哈希表/字典

Perl:从文件生成哈希数组

java - 跳转到其他空位

c++ - 虚函数并强制转换为 void 并返回

c++ - 为什么 python 的 dict 实现为哈希表,而 std::map 是基于树的?