如何在c++中存储泛型元素数组
How to store an array of generic elements in C++?
我试图在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?
table
是void**
,所以table[idx]
是void*
。您的解决方案应该像这样:
((Node<T>*)table[idx])->key
相关文章:
- 错误处理.将系统错误代码映射到泛型
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 链表的泛型函数remove()与成员函数remove)
- 给定一个类型,如何派生一个泛型更广泛的类型(例如,用于溢出安全求和)?
- 模板化接口 - 创建一个泛型模板类以返回任何容器
- 如何编写将要继承的泛型代码?
- C++17 如何保存泛型可调用对象以供以后使用
- 使用宏扩展的泛型:为什么指令缓存使用不当?
- C++泛型类错误,问题出在哪里?
- C++泛型类,单独实现?
- 将参数传递给泛型 lambda 时复制构造函数不正确
- 泛型枚举和其他类型的重载模板函数
- 使用泛型类型推送到堆栈时出现问题
- 可变参数泛型 lambda 和函数重载
- C++ 泛型和多态性:这种模式可行吗?
- 这些语句是否等效(静态变量、常量变量和泛型)
- Java 是否像C++模板一样具有泛型推论?
- 为堆栈实现泛型集合
- 对元组的每个元素进行泛型调用成员函数
- 如何将泛型元素初始化为任意值