我有这段代码用于管理动态集合列表,它主要受 .NET System.List 集合的启发,但这是用普通 C++ 编写的。
void List<T>::Insert(int index, T item)
{
if(index > GetLength() && index >= 0)
throw new StandartException("Index was out of array range");
if(GetLength()==length)
{
T * newl = new T[length + 4];
this->CopyTo(newl);
delete[] this->items;
this->items = newl;
length += 4;
}
T * store = new T[length];
CopyTo(store, index);
store[index] = item;
CopyTo((store + index + 1), index, GetLength() - index);
used++;
delete[] items;
items = store;
}
template <typename T>
void List<T>::CopyTo(T * destination, int start, int count)
{
for(int i = start, c = 0;i < GetLength() && c < count;i++, c++)
*(destination + i) = items[i];
}
所以有方法插入,它必须在数组中的指定索引上插入项目。首先,我正在检查是否在 0 和 Length + 1 之间指定了索引(因为我需要有一个选项来在集合的 ond 上添加项目)。然后我正在测试它是否不是分配数组的结尾(GetLength()=获取数组中的元素数,长度=为元素分配的空间数)。如果是,我正在为数组分配新空间、复制实际元素、释放旧存储并设置指向新地址的指针。
之后,我再次分配新空间。我将实际元素从零复制到索引 - 1,设置必须插入其位置的项目并将其他旧元素复制到它们的索引(它们以前的索引 + 1)。最后,我正在释放旧空间并添加新空间。
错误:我开始调试。一切正常,我第一次运行 Insert 没有问题,但是在第一次删除时(delete[] this->items;
在 if 块中)我收到了这个错误:
有谁知道我为什么会得到这个以及如何修复它?我认为我在任何地方都没有经历过数组范围。请帮忙。