我有这段用于管理动态集合列表的代码,它主要受 .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];
}
所以有 Insert 方法,它必须在数组中的指定索引处插入项目。 首先,我检查是否在 0 和 Length + 1 之间指定了索引(因为我需要有一个选项来在收集的日期添加项目)。然后我测试它是否不是已分配数组的末尾(GetLength() = 获取数组中的元素数,长度 = 为元素分配的空间数)。如果是,我将为数组分配新空间、复制实际元素、释放旧存储并将指针设置为新地址。
之后我再次分配新空间。我正在将实际元素从零复制到索引 - 1,设置必须插入到它的位置的项目并将其他旧元素复制到它们的索引(它们以前的索引 + 1)。最后我要释放旧空间并添加新空间。
错误:我开始调试了。一切正常,我第一次运行 Insert 没有问题,但是在第一次删除时(delete[] this->items;
in if block )我收到了这个错误:
有谁知道我为什么会遇到这个问题,我该如何修复它?我认为我没有在任何地方经历过数组范围。 请帮忙。
最佳答案
你的问题是这一行:
T * store = new T[length];
您插入一个项目,但没有分配比以前更大的数组。当您转到 CopyTo
新数组时,您会溢出数组。
关于c++ - 创建动态集合错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12880021/