在哈希表中调整字符串数组的大小
Resizing string array in hash-table
我现在正在学习哈西。当填充> = 80%时,我正在尝试调整哈希表的大小。但是,每当我尝试调整大小时,我都会得到不确定的行为或崩溃。
我试图制作一个带有更多字段的新字符串数组,然后删除了旧字段,但这不起作用。
Hashtable.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;
};
hashtable.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]);
}
}
有时我的程序进入循环或崩溃。我真的不知道为什么它不起作用。
如果您使用调试器逐步执行程序,则可能会发现resize_array
函数的问题。
将旧表条目复制回新分配的数组时,它使用insert
函数。这有一些问题:
- 由于碰撞分辨率,您可能不会恢复原始值的相同顺序;
-
insert
功能增加了表尺寸,因此它最终会认为它的条目是您最初插入的两倍。
现在,崩溃可能发生,因为insert
将再次触及桌面限制。周期重复直到您要么堆叠溢出或用尽内存。
在您的字符串中复制的正确方法是:
for(int i = 0; i < table_size / 2; i++)
{
T[i] = old_array[i];
}
但是,在任何事情发生之前,还有另一个问题可能会崩溃。您首先保存了您的价值:
for(int i=0; i<table_size;i++)
{
old_array[i]= T[i];
}
请注意,table_size
已经加倍,因此您将访问T
的末尾。您应该改用old_table_size
上的循环。
您还需要一些不必要的复制。如果要重新分配T
,那就这样做:
void hashtable::resize_array()
{
int old_table_size = table_size;
table_size *= 2;
string* old_T = T;
T = new string[table_size];
for (int i = 0; i < old_table_size; i++)
{
std::swap(T[i], old_T[i]); // or in C++11 assign with std::move
}
delete[] old_T;
}
相关文章:
- 使用 jsoncpp 解析 json 数组字符串
- C++ 对象数组字符串输入在控制台上不起作用
- 插入了 C++ 数组字符串数据,但在显示输出时不显示
- 无法区分 JSON 对象/数组/字符串
- 为什么数组(字符串类型)的大小是 24 字节,带有单个空格元素
- 如何使用数组字符串进行输入验证
- (C++) 打印字符数组字符串的单词时出现问题
- 使用Back_inserter从任何位置的输入字符中使用Back_inserter进行过滤数组字符串
- C 函数反转字符数组字符串
- 如何在 c++ 中创建数组(字符串 [] )的向量
- 如何返回数组字符串的指针
- char数组字符串混淆
- 如何从字符数组字符串中提取空格
- 是否可以将 Bitset<8> 的值复制到数组字符串而不转换它们?
- C++数组字符串函数
- 如何在函数中操作字符数组(字符串)的指针,该指针在C / C ++中作为参数传递
- visual将音频文件存储到数组/字符串流C++中
- c++在char数组(字符串)上将what替换为
- 将数组字符串转换为intger c++(初学者)
- 需要设置数组字符串长度,使其恰好为13