使用我的复制构造函数执行哈希表的副本时,例如:
LPTable<int> hashtableCopy = hashtable;
程序崩溃,我不确定为什么。我已经通过了调试器,它似乎知道它在for循环中接收到了什么值,所以我对发生了什么感到困惑,如果它是语法/逻辑问题或什么。非常感谢任何帮助,谢谢。我将发布到目前为止我所尝试的内容。
带有copy ctor的哈希表
template <class TYPE>
class LPTable :public Table<TYPE> {
struct Record {
TYPE data_;
string key_;
bool isDeleted = false;
Record() {
key_ = "";
data_ = 0;
isDeleted = false;
}
Record(const string& key, const TYPE& data) {
key_ = key;
data_ = data;
isDeleted = false;
}
};
Record** records_; //the table
int LargerMax; // *1.35 max_
int max_; //capacity of the array
int size_; //current number of records held
int MyHash(string key); // custom hash function
int numRecords() const { return this.size_; }
bool isEmpty() { return size_ = 0; }
public:
LPTable(int maxExpected);
LPTable(const LPTable& other);
LPTable(LPTable&& other);
virtual bool update(const string& key, const TYPE& value);
virtual bool remove(const string& key);
virtual bool find(const string& key, TYPE& value);
virtual const LPTable& operator=(const LPTable& other);
virtual const LPTable& operator=(LPTable&& other);
virtual ~LPTable();
};
/* none of the code in the function definitions below are correct. You can replace what you need
*/
template <class TYPE>
LPTable<TYPE>::LPTable(int maxExpected) : Table<TYPE>() {
LargerMax = maxExpected * 1.35;
records_ = new Record*[LargerMax];
for (int i = 0; i < LargerMax; i++)
{
records_[i] = nullptr;
}
size_ = 0;
}
//copy ctor
template <class TYPE>
LPTable<TYPE>::LPTable(const LPTable<TYPE>& other) {
records_ = new Record*[other.LargerMax];
for (int i = 0; i < other.LargerMax; i++)
{
while (other.records_[i] != nullptr)
{
records_[i]->key_ = other.records_[i]->key_;
records_[i]->data_ = other.records_[i]->data_;
records_[i]->isDeleted = other.records_[i]->isDeleted;
}
}
}
template <class TYPE>
const LPTable<TYPE>& LPTable<TYPE>::operator=(const LPTable<TYPE>& other)
{
LPTable temp(other);
std::swap(temp.records_, records_);
std::swap(temp.max_, max_);
std::swap(temp.size_, size_);
return *this;
}
template <class TYPE>
const LPTable<TYPE>& LPTable<TYPE>::operator=(LPTable<TYPE>&& other) {
return *this;
}
template <class TYPE>
LPTable<TYPE>::~LPTable() {
delete[] records_;
}
答案 0 :(得分:0)
您永远不会在复制构造函数中设置LargerMax
,max_
或size_
。 (您也不要在构造函数中max_
设置int
。)
复制other.records_
时,您没有为所需的记录分配空间。如果other.records_
中的指针是nullptr
,只需将其设置为records_[i]
中的新指针值,否则将其设置为使用Records复制构造函数分配的新记录。用
while
循环
records_[i] = other.records_[i] == nullptr ? nullptr : new Record(other.records_[i])