C++ C++;哈希表插入函数

C++ C++;哈希表插入函数,c++,C++,我试图实现一个链表向量,但在实现插入函数时遇到了一个问题 类别定义: #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: ve

我试图实现一个链表向量,但在实现插入函数时遇到了一个问题

类别定义:

#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;
#包括
#包括
#包括
使用名称空间std;
类哈希表{
公众:
哈希表(int-size);
无符号整数散列(字符串键);
空白插入(字符串x);
私人:
向量*表;
类实现:

#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.h”
#包括
#包括
#包括
使用名称空间std;
哈希表::哈希表(整数大小){
表=新向量(大小);
}
哈希表::插入(字符串x){
unsigned int index=hash(x);//为了简洁起见,省略了hash函数
表[索引]。推回(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);
hashTable.cpp:38:26:错误:从“字符串”(aka)没有可行的转换
“基本字符串”)到
“常量值类型”(又名“常量”
标准::_1::列表')
表[索引]。推回(x);
向量*pTable=新向量(100);
unsigned int index=3;//假设散列(“AAA”)=3
(*pTable)[index]。向后推(字符串(“AAA”);

上面的代码有效。可能您没有将正确的字符串对象传递到列表对象中。正如@Mooing Duck所说,将vector作为类的成员变量。如果需要,您可以在哈希表类的析构函数中执行相应的内存清理。

这里的
a
是什么,它是通过push\u back插入的?不要
new vector
。这样做从来就没有好的理由。直接将向量作为类的成员。请包含您的类定义。@MooingDuck谢谢您的提示。我现在意识到动态分配可增长数组是没有意义的。
 vector<list<string>>* pTable = new vector<list<string>>(100);
 unsigned int index = 3;//Assume that hash("AAA")=3
(*pTable)[index].push_back(string("AAA"));