【发布时间】:2021-12-27 11:21:29
【问题描述】:
我创建了一个通过创建动态数组来模拟 C++ 向量动作的类,我尝试为该类创建一个推回方法,该方法首先检查数组是否已填充,如果是,它将: 1- 将当前数组的内容复制到双倍大小的临时数组 2-删除旧的动态数组 3-使用旧数组的双倍大小创建一个新的动态数组(临时数组的大小相同) 4- 将临时数组的内容复制到新的动态数组中
错误是当我使用以下代码时,我只能将数组的大小加倍一次,然后它会抛出错误: HEAP [ConsoleApplication1.exe]:指定给 RtlValidateHeap 的地址无效(016C0000、016CDB98) ConsoleApplication1.exe 已触发断点。
#include <iostream>
using namespace std;
class SimpleVector {
private:
int* item; //pointer to the dynamic array (the vector)
int size;
int numElements;
public:
SimpleVector(int size) {
this->size = size;
this->numElements = 0;
this->item = new int[this->size];
}
SimpleVector():SimpleVector(10){}
void pushBack(int element) {
//check for overflow
if (numElements >= size) {
int newSize = size * 2;
int* temp = new int[newSize]; // temporary array with the double size to hold old array elements
for (int i = 0; i < numElements; i++) {
temp[i] = item[i];
}
delete[] item;
size = newSize;
//****ERROR IS IN THIS PART****
int* item = new int[size];
for (int i = 0; i < numElements; i++) {
item[i] = temp[i];
}
//****END OF THE PART CONTAINING ERROR****
item[numElements++] = element;
cout << "Added: " << element << endl;
cout << "Size is: " << size << endl;
}
else {
item[numElements++] = element;
cout << "Added: " << element << endl;
cout << "Size is: " << size << endl;
}
}
};
int main() {
SimpleVector v1(2);
v1.pushBack(1);
v1.pushBack(2);
v1.pushBack(3);
v1.pushBack(4);
v1.pushBack(5);
v1.pushBack(6);
v1.pushBack(7);
return 0;
}
此程序推送前 4 个项目,然后在尝试将尺寸加倍为 8 时引发错误
当我将包含错误的部分替换为:
item = temp
它工作正常,但我不明白为什么会发生这种情况。
【问题讨论】:
标签: c++ arrays class oop vector