2016-03-04 24 views
-2

我試圖實現一個鏈接列表的矢量,但我在實現插入函數時遇到問題。C++ HashTable插入函數

類定義:

#include <vector> 
#include <list> 
#include <string> 
using namespace std; 

class HashTable { 
public: 
    HashTable(int size); 
    unsigned int hash(string key); 
    void insert(string x); 

private: 
    vector<list<string> >* table; 

類實現:

#include "hashTable.h" 
#include <string> 
#include <list> 
#include <vector> 
using namespace std; 

HashTable::HashTable(int size) { 
    table = new vector<list<string> >(size); 
} 

HashTable::insert(string x){ 
    unsigned int index = hash(x); //left out the hash function for brevity 
    table[index].push_back(x); 


} 

我得到的錯誤:

hashTable.cpp:38:26: error: no viable conversion from 'string' (aka 
     'basic_string<char, char_traits<char>, allocator<char> >') to 
     'const value_type' (aka 'const 
     std::__1::list<std::__1::basic_string<char>, 
     std::__1::allocator<std::__1::basic_string<char> > >') 
    table[index].push_back(x); 
+0

什麼是'a',這是通過push_back插入的? –

+1

不要'新的矢量'。有一個很好的理由這樣做。使矢量直接成爲該類的成員。 –

+0

請包括您的班級定義。 – kfsone

回答

1
vector<list<string>>* pTable = new vector<list<string>>(100); 
unsigned int index = 3;//Assume that hash("AAA")=3 
(*pTable)[index].push_back(string("AAA")); 

上述工程的代碼。可能您沒有將適當的字符串對象傳遞給列表對象。正如@Mooing Duck所說,使vector成爲該類的成員變量。如果需要,可以在Hash Table類的析構函數中清理相應的內存。