我遇到了我正在尝试构建的哈希表问题。它应该有一个Linked List数组,每当我调用我为它构建的insertLast函数时,我都会遇到转换错误:
无法将参数1从'KeyValue *'转换为'const T&'。
从我在试图解决这个问题时看到的东西被正确宣布但我无法确定问题所在或者是否正确。任何帮助是极大的赞赏。这是一个家庭作业,所以我要求你只是帮我识别这个问题,如果还有什么其他方法我会宁愿发现自己。
//hash table class
template <typename K, typename V>
class HashTable
{
friend class LinkedList<KeyValue<K,V>>;
public:
HashTable(const int& bucketCount);
~HashTable();
int buckets;
LinkedList<KeyValue<K, V>> * arr{ nullptr };
void add(const K& key, const V& value);
};// end class HashTable
template<typename K, typename V>
HashTable<K, V>::HashTable(const int& bucketCount) {
buckets = bucketCount;
this->arr = new LinkedList<KeyValue<K, V>>[buckets];
}
template <typename K, typename V>
HashTable<K, V>::~HashTable() {
delete[] arr;
}
template <typename K, typename V>
void HashTable<K, V>::add(const K& key, const V& value) {
//this is the line of code that breaks
arr[std::hash<K>{}(key) % buckets].insertLast(new KeyValue<K, V>(key, value));
}
这是我的具有insertLast函数的链表类
//LinkedList class
template <typename T>
class LinkedList
{
public:
~LinkedList();
void insertLast(const T& value);
Iterator<T> begin();
Iterator<T> end();
protected:
Node<T> *front{ nullptr };
Node<T> *back{ nullptr };
int count{ 0 };
};
template <typename T>
LinkedList<T>::~LinkedList() {
if (this->front) {
Node<T> * temp{ this->front->forward };
while (temp) {
delete this->front;
this->front = temp;
temp = temp->forward;
}
delete this->front;
}
}
//this is the function I'm getting an error on
template <typename T>
void LinkedList<T>::insertLast(const T& value) {
Node<T> * temp = new Node<T>();
temp->data = value;
if (!this->front) {
// Specific scenario, list is empty
this->front = temp;
}
else {
// General scenario, at least one node
this->back->forward = temp;
}
this->back = temp;
this->count++;
}
这是我的KeyValue类,该表将包含一个KeyList数组,其类型为KeyValue
//KeyValue class
template <typename K, typename V>
class KeyValue {
public:
K key{};
V value{};
KeyValue();
KeyValue(const K& key, const V& value);
};
template <typename K, typename V>
KeyValue<K, V>::KeyValue() {
}
template <typename K, typename V>
KeyValue<K, V>::KeyValue(const K& key, const V& value) {
this->key = key;
this->value = value;
}
请注意,您的LinkedList
变量定义为
LinkedList<KeyValue<K, V>> * arr{ nullptr };
在HashTable
类中,这意味着这是指向包含LinkedList
的KeyValues<K, V>
的指针
insertLast
函数定义为:
void insertLast(const T& value);
其中T
是LinkedList
类的模板类型,即KeyValue<K, V>
。
另一方面,您正在尝试使用insertLast
函数
arr[std::hash<K>{}(key) % buckets].insertLast(new KeyValue<K, V>(key, value));
在这里,new KeyValue<K, V>(key, value)
是KeyValue<K, V>*
,其中insertLast
函数期望const KeyValue<K, V>&
。
如果你在这里删除new
关键字,它应该工作,因为将创建一个新对象,然后在insertLast
函数内复制。