C++哈希表插入功能

C++ HashTable Insert Function

本文关键字:功能 插入 哈希表 C++      更新时间:2023-10-16

我正在尝试实现链表向量,但是在实现插入函数时遇到了问题。

类定义:

#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);
 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所说,使向量成为类的成员变量。如果需要,可以在哈希表类的析构函数中执行相应的内存清理。