【发布时间】:2016-11-21 00:56:42
【问题描述】:
我正在尝试在这里编写 HashTable。我已经对所有函数进行了几乎所有的编码,并且程序正在使用 main 编译。但由于某种原因,我的 find 函数需要永远与我拥有的 main 一起运行。此外,当测试复制构造函数和 operator= 时,程序崩溃了。下面是哈希表
structure
{
struct Record
{
TYPE data_;
string key_;
Record* Next ;
Record(const string& key, const TYPE& data)
{
key_ = key;
data_ = data;
}
Record()
{
key_ = "" ;
Next = nullptr;
}
};
int TableSize ;
Record** records ;
template <class TYPE>
bool HashTable<TYPE>::find(const string& key, TYPE& value)
{
// int index = std::hash<TYPE> {}(value)%TableSize ;
int index = std::hash<string> {}(key)%TableSize ;
Record* temp = records[index] ;
while(temp != nullptr )
{
if(temp->data_ == value && temp->key_ == key)
return true ;
temp = temp->Next ;
}
return false ;
}
operator=
template <class TYPE>
const HashTable<TYPE>& HashTable<TYPE>::operator=(const HashTable<TYPE>& other)
{
if(this != &other)
{
if(records)
{
for(int i = 0 ; i < TableSize; i++)
remove(records[i]->key_);
delete[] records ;
}
records = new Record*[other.TableSize] ;
TableSize = other.TableSize ;
for(int i = 0 ; i < other.TableSize ; i++)
{
update(records[i]->key_, records[i]->data_);
}
}
return *this;
}
template <class TYPE>
HashTable<TYPE>::HashTable(const HashTable<TYPE>& other)
{
if(other.records != nullptr)
{
if(records)
{
delete[] records ;
cout<<"delete"<<endl;
}
records = new Record*[other.TableSize];
TableSize = other.TableSize;
for(int i = 0 ; i < other.TableSize; i++)
records[i] = new Record();
for (int i = 0; i<other.TableSize; i++)
{
update(other.records[i]->key_, other.records[i]->data_);
}
}
else
{
records = nullptr;
}
}
【问题讨论】: