【发布时间】:2017-03-28 19:45:44
【问题描述】:
所以,我真的迷路了。我在尝试将项目插入哈希表时非常困难,insert(const Entry& e) 我在下面发布了我最近的尝试,我知道这并不多,但到目前为止,这就是我所得到的。任何朝着正确方向的推动都非常感谢。
我的结构和类定义应该没问题。
目前正在获取,
hTable.cc:在成员函数'void HT::insert(const Entry&)'中:
hTable.cc:38:19:错误:'operator=' 不匹配
当我这样做时发生错误,hTable[hashVal] = new Entry(e);
和
hTable.cc:37:57:从这里需要
/usr/include/c++/5/bits/predefined_ops.h:234:30: 错误:表达式不能是
用作函数
{ return bool(_M_pred(*__it)); }
第二个错误来自我使用find_if() 的同一行,我认为它与我使用hashVal 的方式有关?我确实查了find_if(),但很多解释对我来说没有多大意义。
下面是我的结构,表中的条目(Entry.h)
#ifndef H_ENTRY
#define H_ENTRY
#include <string>
using namespace std;
#define ID_SZ 3 // size of key
#define ITEM_SZ 24 // max size for item description
#define TBL_SZ 31 // default size for hash table
struct Entry {
string key, // key
desc; // description
unsigned num; // no of copies
//constructor
Entry ( const string& k = "", const string& d = "",
const unsigned& n = 0 ) : key ( k ), desc ( d ),
num ( n ) { }
};
#endif
下面是我的哈希表 (hTable.h) 的类定义
#include "Entry.h"
#ifndef H_HASH_TABLE
#define H_HASH_TABLE
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <list>
#include <vector>
class HT {
public:
HT ( const unsigned& = TBL_SZ ); // constructor
~HT ( ); // destructor
void insert ( const Entry& ); // inserts item in hash table
private:
unsigned hsize; // size of hash table
vector < list < Entry > > hTable; // hash table
vector < Entry* > pTable; // ptr table
int hash ( const string& ); // hash function
};
#endif
下面是我的 hTable.cc,我的问题出在哪里。
#include "hTable.h"
HT::~HT() {
for (unsigned i = 0; i < hsize; i++)
hTable.pop_back();
}
HT::HT(const unsigned& hs) {
hTable.resize(hs);
pTable.resize(hs);
}
void HT::insert(const Entry& e) {
//if key already exists, print out message saying so.
//else, insert into hash table
//also inserts the address of the record (in the hash table) into the pointer table
int hashVal = hash(e.key);
if( find_if( hTable.begin(), hTable.end(), hashVal) == hTable.end() )
hTable[hashVal] = new Entry(e);
else
cout << "\ntemp message\n";
}
【问题讨论】:
-
您是否收到任何错误消息,告诉您它无法正常工作?这可能对我们有帮助。继续努力,你会成功的!
-
进入并添加了我收到的错误消息!
-
您遇到的问题不仅仅是
insert()函数。您到处都有重大错误,例如在析构函数中使用的未初始化的类成员,而一开始就不需要在析构函数中使用它们。 -
但是由于哈希表被实现为列表容器的向量,我不需要释放列表容器的所有内存并释放向量容器的内存(我的哈希表和指针表)?
-
不需要手动从容器中移除任何东西。它的析构函数会处理它。唯一需要做任何事情的时候是使用指向在动态范围内分配的对象的指针容器。但在这种情况下,应该使用
std::shared_ptr,无论如何,它会为你做这件事。现代 C++ 代码几乎不需要使用new和delete,容器负责处理一切。