【发布时间】:2019-10-07 10:29:41
【问题描述】:
我现在正在学习散列。我正在尝试在填充 >=80% 时调整我的哈希表的大小。但是每次我尝试调整它的大小时,我都会得到未定义的行为或崩溃。
我尝试创建一个包含更多字段的新字符串数组,然后我删除了旧的但没有用。
哈希表.h
class hashtable
{
public:
hashtable();
void insert(string);
void resize_array();
int hashfunction(string str);
string* getArray();
private:
int elemts_in_array;
int table_size;
string* T;
};
哈希表.cpp
hashtable::hashtable()
{
// your code (start with a capacity of 10)
table_size = 10;
elemts_in_array = 0;
string *array = new string[table_size];
T = array;
}
void hashtable::insert(string key)
{
string* array = getArray();
int hkey=hashfunction(key);
float filled = float(elemts_in_array)/float(table_size);
// When the array is more than 80% filled resize it and double the table_size
if(filled >= 0.8)
{
cout << "Resizing Array.." << endl;
resize_array();
}
for(int i=0; i<table_size;i++)
{
// if the field is empty insert it, else go +1
if(array[(hkey+i)%table_size] == "")
{
array[(hkey+i)%table_size] = key;
elemts_in_array++;
break;
}
if(array[(hkey+i)%table_size] == key)
{
// it is the same element
break;
}
}
}
void hashtable::resize_array()
{
int old_table_size =table_size;
table_size*=2; // double the size of the hashtable
string* old_array= new string[table_size]; // save the old array entries
old_array = T;
// Apply the old entries in old_array
for(int i=0; i<table_size;i++)
{
old_array[i]= T[i];
}
//create a new array with double size
string *new_array = new string[table_size];
//delete the old T
delete[] T;
T = new_array;
//re-hash the old entries into the new array with double size (HERE I GOT THE ISSUES)
for(int i=0; i<table_size/2; i++)
{
insert(old_array[i]);
}
}
有时我的程序会进入循环或崩溃。我真的不知道为什么它不起作用。
【问题讨论】:
-
最明显的违规者是
old_array = T;,然后是delete[] T;,最后是一个循环执行insert(old_array[i]);一旦你delete[] Told_array留下一个悬空指针,钻入它会调用UB。撒盐,您在该函数中也有内存泄漏,因为string* old_array= new...在下一行泄漏。 -
哦,嘿嘿,我直接看过去了那个作业,发现了一堆其他问题