我的哈希表类的构造函数出错了,这是一个'Entry'对象的向量(下面的类定义)。
HT::HT ( const unsigned& s )
{
hTable = new Entry[s];
pTable = new Entry*[s];
psize = 0;
hsize = TBL_SZ;
for (unsigned int i = 0; i != s; i++)
{
hTable[i].key = FREE;
}
}
为什么我收到此错误?
hTable.cc:12:15: error: expected type-specifier before âhTableâ
hTable.cc:12:15: error: no match for âoperator=â in â((HT*)this)->HT::hTable = (int*)operator new(4u)â
hTable.cc:12:15: note: candidate is:
/usr/include/c++/4.6/bits/vector.tcc:158:5: note: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(const std::vector<_Tp, _Alloc>&) [with _Tp = Entry, _Alloc = std::allocator<Entry>]
/usr/include/c++/4.6/bits/vector.tcc:158:5: note: no known conversion for argument 1 from âint*â to âconst std::vector<Entry>&â
hTable.cc:12:15: error: expected â;â before âhTableâ
hTable.cc:13:15: error: expected type-specifier before âpTableâ
hTable.cc:13:15: error: no match for âoperator=â in â((HT*)this)->HT::pTable = (int*)operator new(4u)â
hTable.cc:13:15: note: candidate is:
/usr/include/c++/4.6/bits/vector.tcc:158:5: note: std::vector<_Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(const std::vector<_Tp, _Alloc>&) [with _Tp = Entry*, _Alloc = std::allocator<Entry*>]
/usr/include/c++/4.6/bits/vector.tcc:158:5: note: no known conversion for argument 1 from âint*â to âconst std::vector<Entry*>&â
这是头文件:
#ifndef H_HASH_TABLE
#define H_HASH_TABLE
// class for hash table
class HT {
public:
HT ( const unsigned& = TBL_SZ ); // constructor
~HT ( ); // destructor
void insert ( const Entry& ); // inserts item in hash table
void search ( const string& ); // searches for item
void hTable_print ( ); // prints hash table entries
void pTable_print ( ); // prints hash table entries in sorted order
private:
unsigned hsize, // size of hash table
psize; // actual size of ptr table
vector < Entry > hTable; // hash table
vector < Entry* > pTable; // ptr table
int hash ( const string& ); // hash function
};
#endif
这是我的Entry对象标题:
#ifndef H_ENTRY
#define H_ENTRY
#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
#define FREE "$$$" // indicates empty spot in hash table
// entry in hash table
struct Entry {
string key; // key
string desc; // description
unsigned num; // no of copies
//constructor
Entry ( const string& k = FREE, const string& d = "",
const unsigned& n = 0 ) : key ( k ), desc ( d ),
num ( n ) { }
};
#endif
答案 0 :(得分:0)
成员的声明
vector < Entry > hTable; // hash table
vector < Entry* > pTable; // ptr table
与初始化完全匹配
hTable = new Entry[s];
pTable = new Entry*[s];
std::vector
不是指针,不应使用new
创建。它们由vector
构造函数自动初始化。
如果要设置向量的大小,可以在构造函数初始化列表中执行此操作,或者通过调整默认构造向量的大小:
HT::HT ( const unsigned& s )
{
hTable.resize(s);
pTable.resize(s);
psize = 0;
hsize = TBL_SZ;
for (unsigned int i = 0; i != s; i++)
{
hTable[i].key = FREE;
}
}
答案 1 :(得分:0)
new Entry[s];
创建一个Entry对象数组,并尝试将其分配给向量。新的Entry * [s]也是如此。您需要确定hTable和pTables是否需要是向量或用
Entry *hTable
Entry **pTable
。