2013-04-02 5 views
0

Я должен создать шаблонный hashTable, однако всякий раз, когда я пытаюсь его скомпилировать, я получаю несколько ошибок, говорящих о необъявленных идентификаторах, и что шаблоны не являются именами, когда они есть. Проблема конкретно в классе hashTable.Проблемы с реализацией шаблона hashTable

//Author: Angelo Todaro 
//hashTable.h 
//File for the implementation of the hash table 

#include "person.h" 
#include "student.h" 
#include "administrator.h" 
#include "faculty.h" 
#include <list> 

using namespace std; 
#ifndef hashTable_H 
#define hashTable_H 


template<class T, typename T2, typename T3> 
class hashTable{ 
public: 
    /*Default Constructor 
    *Constructs an object of the hashTable class*/ 
    hashTable(); 

    /*Default Destructor 
    *Destructs an object of the hashTable class*/ 
    ~hashTable(); 


    /*Accessor Method for size of table 
    *Provides user access to the value of the size of the table*/ 
    T getSize() const; 

    /*Modifier Method for size of table 
    *Provides the user access to change the value of the size of the table*/ 
    void setSize(T newSize); 

    /*getEntry 
    *Retrieves an entry from the table based on the key*/ 
    T2 getEntry(T3 searchEntry); 

    /*putEntry 
    *Puts a new entry in its proper location in the table*/ 
    void putEntry(T2 newEntry); 

    /*removeEntry 
    *Removes an entry from its location in the table*/ 
    void removeEntry(T3 searchEntry); 

private: 
    T size; 
    list<T2> table[size]; 
    list<T2>::iterator iter; 

    /*hashKey 
    *Hashes the given key in order to find its location in the table*/ 
    T hashKey(T3 key); 

}; 

#endif 

//Implementation section 


    /*Default Constructor 
    *Constructs an object of the hashTable class*/ 
    template<typename T, typename T2, typename T3> 
    hashTable<T,T2,T3>::hashTable(){ 

    } 

    /*Default Destructor 
    *Destructs an object of the hashTable class*/ 
    template<typename T, typename T2, typename T3> 
    hashTable<T,T2,T3>::~hashTable(){ 

    } 


    /*Accessor Method for size of table 
    *Provides user access to the value of the size of the table*/ 
    template<typename T, class T2, class T3> 
    T hashTable<T,T2,T3>::getSize() const{ 
     return size; 
    } 

    /*Modifier Method for size of table 
    *Provides the user access to change the value of the size of the table*/ 
    template<typename T, typename T2, typename T3> 
    void hashTable<T,T2,T3>::setSize(T newSize){ 
     size = newSize; 
    } 

    /*getEntry 
    *Retrieves an entry from the table based on the key*/ 
    template<typename T, typename T2, typename T3> 
    T2 hashTable<T,T2,T3>::getEntry(T3 searchEntry){ 
     int key = hashKey(searchEntry); 
     if(table[key]==NULL) 
     { 
      return -1; 
     } 
     else 
     { 
      while(iter != table[key].end() || searchEntry != *iter->getKey()) 
       iter++; 
      if(iter == table[key].end() && searchEntry != *iter->getKey()) 
      { 
       return -1; 
      } 
      else 
      { 
       *iter->print(); 
      } 
     } 
    } 

    /*putEntry 
    *Puts a new entry in its proper location in the table*/ 
    template<typename T, typename T2, typename T3> 
    void hashTable<T,T2,T3>::putEntry(T2 newEntry){ 
     int key = hashKey(newEntry->getKey()); 
     table[key].push_back(newEntry); 
    } 

    /*removeEntry 
    *Removes an entry from its location in the table*/ 
    template<typename T, typename T2, typename T3> 
    void hashTable<T,T2,T3>::removeEntry(T3 searchEntry){ 
     int key = hashKey(searchEntry); 
     while(iter != table[key].end() || searchEntry != *iter->getKey()) 
      iter++; 
     if(*iter->getKey() == searchEntry) 
      table[key].erase(iter); 
     else 
      cout << "Can not delete Person (M" << number << "), NOT found!" << endl; 
    } 

    /*hashKey 
    *Hashes the given key in order to find its location in the table*/ 
    template<typename T, typename T2, typename T3> 
    T hashTable<T,T2,T3>::hashKey(T3 key){ 
      return key/1000; 
    } 

Вот ошибки, которые я получаю

1>------ Build started: Project: lab12, Configuration: Debug Win32 ------ 
1>Build started 4/2/2013 3:20:56 PM. 
1>InitializeBuildStatus: 
1> Touching "Debug\lab12.unsuccessfulbuild". 
1>ClCompile: 
1> recordsOffice.cpp 
1>c:\users\angelo\google drive\advanced data structures\lab12\lab12\hashtable.h(50): error C2327: 'hashTable<T,T2,T3>::size' : is not a type name, static, or enumerator 
1>   c:\users\angelo\google drive\advanced data structures\lab12\lab12\hashtable.h(57) : see reference to class template instantiation 'hashTable<T,T2,T3>' being compiled 
1>c:\users\angelo\google drive\advanced data structures\lab12\lab12\hashtable.h(50): error C2065: 'size' : undeclared identifier 
1>c:\users\angelo\google drive\advanced data structures\lab12\lab12\hashtable.h(51): warning C4346: 'std::list<T2>::iterator' : dependent name is not a type 
1>   prefix with 'typename' to indicate a type 
1>c:\users\angelo\google drive\advanced data structures\lab12\lab12\hashtable.h(51): error C2146: syntax error : missing ';' before identifier 'iter' 
1>c:\users\angelo\google drive\advanced data structures\lab12\lab12\hashtable.h(51): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int 
1>c:\users\angelo\google drive\advanced data structures\lab12\lab12\hashtable.h(50): error C2327: 'hashTable<T,T2,T3>::size' : is not a type name, static, or enumerator 
1>   with 
1>   [ 
1>    T=int, 
1>    T2=Person, 
1>    T3=int 
1>   ] 
1>   c:\users\angelo\google drive\advanced data structures\lab12\lab12\recordsoffice.h(35) : see reference to class template instantiation 'hashTable<T,T2,T3>' being compiled 
1>   with 
1>   [ 
1>    T=int, 
1>    T2=Person, 
1>    T3=int 
1>   ] 
1>c:\users\angelo\google drive\advanced data structures\lab12\lab12\hashtable.h(50): error C2065: 'size' : undeclared identifier 
1> lab12-main.cpp 
1>c:\users\angelo\google drive\advanced data structures\lab12\lab12\hashtable.h(50): error C2327: 'hashTable<T,T2,T3>::size' : is not a type name, static, or enumerator 
1>   c:\users\angelo\google drive\advanced data structures\lab12\lab12\hashtable.h(57) : see reference to class template instantiation 'hashTable<T,T2,T3>' being compiled 
1>c:\users\angelo\google drive\advanced data structures\lab12\lab12\hashtable.h(50): error C2065: 'size' : undeclared identifier 
1>c:\users\angelo\google drive\advanced data structures\lab12\lab12\hashtable.h(51): warning C4346: 'std::list<T2>::iterator' : dependent name is not a type 
1>   prefix with 'typename' to indicate a type 
1>c:\users\angelo\google drive\advanced data structures\lab12\lab12\hashtable.h(51): error C2146: syntax error : missing ';' before identifier 'iter' 
1>c:\users\angelo\google drive\advanced data structures\lab12\lab12\hashtable.h(51): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int 
1>c:\users\angelo\google drive\advanced data structures\lab12\lab12\hashtable.h(50): error C2327: 'hashTable<T,T2,T3>::size' : is not a type name, static, or enumerator 
1>   with 
1>   [ 
1>    T=int, 
1>    T2=Person, 
1>    T3=int 
1>   ] 
1>   c:\users\angelo\google drive\advanced data structures\lab12\lab12\recordsoffice.h(35) : see reference to class template instantiation 'hashTable<T,T2,T3>' being compiled 
1>   with 
1>   [ 
1>    T=int, 
1>    T2=Person, 
1>    T3=int 
1>   ] 
1>c:\users\angelo\google drive\advanced data structures\lab12\lab12\hashtable.h(50): error C2065: 'size' : undeclared identifier 
1> Generating Code... 
1> 
1>Build FAILED. 
1> 
1>Time Elapsed 00:00:01.84 
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== 
+0

Как вы используете эту хеш-таблицу? Я спрашиваю, потому что в игре есть три разных типа шаблонов ('T' размер,' T2', что вы храните, и 'T3', что вы хотите найти хранимый' T2'). Некоторые из них кажутся ненужными. Вероятно, 'T' (размер) должен быть просто' size_t' (поэтому _not_ templated). Почему размер аргумента шаблона? Что делать, если я использую вашу хеш-таблицу и предоставляю 'T' =' std :: string'? 'T3' не является строго необходимым (вы должны иметь возможность находить' T2', используя 'T2', но может иметь смысл, если' T2' не является тривиальным для построения. – Chad

+0

Если вы заархивировали 'T' как размер, потому что вы хотите, чтобы размер хеш-таблицы настраивался во время компиляции, вы не должны использовать здесь имя-тип, вместо этого используйте size_t. Например: http://ideone.com/2RCc1M – Chad

+0

Единственная причина, по которой T3 является шаблоном, состоит в том, что T2 - это класс который содержит несколько разных ints и строк, T3 просто упрощает, если я решил использовать строки вместо int для индексирования. – todaroa

ответ

1

Проблемы здесь

private: 
    T size; 
    list<T2> table[size]; 
    list<T2>::iterator iter; 

1 Это неправильно.

list<T2> table[size]; 

То есть не так, как объявляются списки. И даже если это был обычный массив, вы не можете использовать size, потому что размер не static. Компилятор не знает значения size при создании экземпляра hashTable для выделения массива.

Должно быть просто

list<T2> table; 

2 Это необходимо TYPENAME

list<T2>::iterator iter; 

компилятор должен знать, что вы объявляете iter и ожидает спецификатор типа. Вы можете помочь ему, добавив typename в декларацию.

Должно быть

typename list<T2>::iterator iter; 

Так summerize

T size; 
list<T2> table; // HERE 
typename list<T2>::iterator iter; // HERE 

если вы хотите массив списков (не один список). вы можете использовать вектор (вместо массива) списков.

vector< list<T2> > table; OR 
list< list<T2> > table; 

(в зависимости от ваших потребностей. More info on containers)

Но будьте осторожны с этим. Копирование этих объектов может быть дорогостоящим. Передавайте по ссылкам или используйте указатели, когда сможете.

+0

Итак, чтобы создать массив списков, я должен просто сделать это в конструкторе? – todaroa

+0

Я отредактировал ответ. – 2013-04-02 21:08:58

+0

Хорошо, что делает его намного понятнее. Мы просто изучили STL, и я даже не думал использовать вектор вместо массива. – todaroa

Смежные вопросы