哈希表在增加大小后重新插入
Hash Table reinserting after increasing in size
我一直在研究这个哈希表的实现,但我遇到了一个障碍。我修改了构造函数和插入函数,以便在容量达到时能够调整数组的大小,但我在调整大小时遇到了问题。现在,它似乎在无限地插入负面数据,我不知道为什么。我应该在resize中实现迭代器还是有更简单的方法?
函数如下:
调整:
template <class RecordType>
void table<RecordType>::resize( )
{
RecordType *oldData = data;
int oldSize = CAPACITY;
int newSize = CAPACITY *2;
//create a new table
RecordType *newData;
newData = new RecordType[CAPACITY];
size_t i;
used = 0;
for (i = 0; i < CAPACITY; i++)
newData[i].key = NEVER_USED;
data = newData;
delete[] newData;
//place data from old table to new, larger table.
for(int i = 0; i < oldSize; i++)
{
RecordType next = oldData[i];
insert(next);
}
CAPACITY = newSize;
delete[] oldData;
}
构造函数:
template <class RecordType>
table<RecordType>::table( )
{
CAPACITY = 30;
data = new RecordType[CAPACITY];
size_t i;
used = 0;
for (i = 0; i < CAPACITY; ++i)
data[i].key = NEVER_USED;
}
插入:template <class RecordType>
void table<RecordType>::insert(const RecordType& entry)
// Library facilities used: cassert
{
bool already_present; // True if entry.key is already in the table
size_t index; // data[index] is location for the new entry
assert(entry.key >= 0);
// Set index so that data[index] is the spot to place the new entry.
find_index(entry.key, already_present, index);
// If the key wasn't already there, then find the location for the new entry.
if (!already_present)
{
if (size( ) >= CAPACITY)
{
resize( ); // resize the table.
insert(entry); // reinsert entry into new table.
}
else if (size( ) < CAPACITY)
{
index = hash(entry.key);
while (!is_vacant(index))
index = next_index(index);
++used;
}
}
data[index] = entry;
size_t i;
for (i=0; i<CAPACITY; i++) cout << data[i].key << ' ';
cout << endl;
}
谢谢你的帮助!
您的resize()
正在调用将数据放入data[]
的insert()
。然后resize()
用空的(充满NEVER_USED
的)newData
数组覆盖data
。我的猜测是,你想摆脱newData
,只使用data
代替。
您可能也应该重新考虑CAPACITY *= CAPACITY
,因为当您尝试将此代码用于实际内容时,这将会爆炸。
相关文章:
- 在二叉搜索树中插入新元素
- 插入容器的容器(如果是新的或附加到现有容器)
- 插入新键时,它会更改现有键值的地址吗?
- 如果我们不创建一个新节点并使用指针插入数据并建立链接(在链表中)怎么办?
- 如何在使用 ItemType 的模板类时将新节点插入二叉树 c++.(我是 c++ 的新手)
- 在 std::unordered_map 中插入新的键/值对会导致"out of range"异常
- 有没有办法通过插入新类型名称而不是 int 来使用 2 位大小类型而不是 int?
- 通过字符串::插入插入字符时出错
- 在指向对象的指针的动态数组上插入新元素
- 在动态分配的二维矩阵中插入新列
- 新元素将在std :: set中插入哪里
- 在unordered_map/unordered_set中插入/放置新元素时的提示
- 插入新元素时结束迭代器会获得更新
- 将unordered_map的新实例插入到unordered_map中
- 新的STD :: MAP条目如何仅通过键插入初始化
- 在插入后与插入插入插件后对矢量进行排序
- C++链表——如何将每个新数据插入尾部
- 将新元素插入哈希表
- 在运行递归函数时将新元素插入向量时出现问题
- 为什么在尝试将新节点插入列表时出错