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

时间:2015-11-05 13:19:28

标签: c++ templates arguments hashtable

我正在编写一个程序来创建一个哈希表,同时提供了从表中插入和删除值的选项。我很快就会添加一个选项来为所有数据类型创建一个新表,需要为哈希表类使用一个模板。但是这个错误消息"错误:使用类模板' 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

2 个答案:

答案 0 :(得分:1)

您想要散列的是哪种类型?决定这一点。我们说它是Y。然后你需要替换

HashTable hash;

HashTable<Y> hash;

如果您希望Y成为std::string,那么您还有一些工作要做。对于字符串类型,hashValue % 100将毫无意义。考虑使用std::hash代替?然后将整个事物分开并使用std::unordered_map

答案 1 :(得分:0)

您需要指定模板参数T

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