错误:使用类模板'HashTable'需要模板参数

error: use of class template 'HashTable' requires template arguments

本文关键字:参数 HashTable 错误      更新时间:2023-10-16

我正在编写一个程序来创建哈希表,同时提供从表中插入和删除值的选项。我很快将添加一个选项,为所有数据类型创建一个新表,这需要使用哈希表类的模板。但这个错误消息"错误:使用类模板‘HashTable’需要模板参数"不断出现,有人知道为什么吗?非常感谢。

#include <vector>
#include <iostream>
#include <string>
using namespace std;
// ------------ Hash table ------------
template <class T>
class HashTable{
    private:
        vector<T> arrayofbuckets[100];
    public:
         void insertelement(string input);
         void deleteelement(string remove);
}; // end of class
// ------------ MAIN ------------ 
int main()
{
HashTable hash;
// Creating the menu
char selection;
string Element;
string ElementDelete;
do{
cout << "--------------- Menu ---------------";
cout << "n Press i to insert an element into the hash table";
cout << "n Press d to delete an element from the hash table";
// Read the input
cin >> selection;
switch(selection)
{
// Inserting an element
case 'I':
case 'i':
{
    cout << " Which element would you like to insert?: ";
    cin >> Element;
    hash.insertelement(Element);
    }
break;
// Delete an element
case 'D':
case 'd':
{
    cout << " Which element would you like to delete?: ";
    cin >> ElementDelete;
    hash.deleteelement(ElementDelete);
    }
break;

// Exit the program
case 'e': {cout << "Goodbye! :D";}
break;
// Display message if input is not I, D, L, S, P or E
default : cout << "n Invalid selection";
}
cout<<"n";
} while(selection != 'e');
return 0;
} // End of main
// ------------ Functions for chained hash tables ------------
// Inserting an element
template <class T>
void HashTable<T>::insertelement(string input){
    T hashValue = 0;
    for(int i = 0; i<input.length(); i++){
        hashValue = hashValue + int(input[i]);
    }
    hashValue = hashValue % 100; // HASH FUNCTION
    arrayofbuckets[hashValue].push_back(input);
    cout << " The element " << input << " has been put into value " << hashValue << endl;
} // End of insert function
// Deleting an element
 template <class T>
 void HashTable<T>::deleteelement(string remove){
    T hashValue = 0;
    for(int i = 0; i < remove.length(); i++){
        hashValue = hashValue + int(remove[i]);
    }
    hashValue = hashValue % 100; // HASH FUNCTION
    for (unsigned int i=0; i<arrayofbuckets[hashValue].size();){
        if (arrayofbuckets[hashValue].at(i)==remove){
            arrayofbuckets[hashValue].erase(arrayofbuckets[hashValue].begin()+i);
    cout << " The element " << remove << " has been deleted from bucket " << hashValue << endl;
 } else {
            i++;
 }
}
} // End of delete function

您想要哈希的类型是什么?决定吧。假设它是Y。然后你需要更换

HashTable hash;

带有

HashTable<Y> hash;

如果你想让Y成为std::string,那么你还有一些工作要做。hashValue % 100对于字符串类型来说毫无意义。是否考虑改用std::hash?然后将整个东西装箱并使用std::unordered_map

您需要指定模板参数T:

HashTable<string> hash;
      // ^^^^^^^^