C++中数组的动态调整大小
Dynamic resizing of an array in C++
我有一个类,其中包含指向Airport对象的项。动态数组的大小从10开始。当total
大于数组的大小,并且我已经读取了数据来填充数组时,我需要将数组的大小增加一倍,将旧数组中的元素复制到新大小的数组中,然后删除旧数组。数组将继续读入数据,然后调整大小,并继续这样做,直到文件中的所有数据都读入items
数组。
没有出现错误,但问题是当我运行程序时,它会崩溃。我认为doubleSize
函数调整数组大小可能是造成这种情况的原因。有办法解决这个问题吗?
class AirportList
{
private:
Airport* items;
int total;
int maxElements;
int oldAmount;
public:
AirportList()
{
oldAmount = 10;
maxElements = 10;
items = new Aiport[maxElements];
// a file was opened to read in data before this,
// total equals the total amount of lines in the file
string cppstr;
for (int counter = 0; counter < total; counter++)
{
getline(infile, cppstr);
items[counter] = Airport(cppstr); // the Airport constructor
// parses each line to read in
// the data and sets each Airport
// object into the items array
if (total > maxElements && counter == maxElements)
doubleSize(items, maxElements, oldAmount);
}
infile.close();
}
void doubleSize(Airport*& orig, int maxElements, int oldAmount)
{
maxElements = maxElements * 2;
Aiport* resized = new Aiport[maxElements];
for (int i = 0; i < oldAmount; i++)
resized[i] = orig[i];
delete [] orig;
orig = resized;
oldAmount = maxElements;
}
};
在对counter == maxelements
所在的数组进行赋值之前,不会将大小加倍,但items[maxelements]
无效——只有maxelements - 1
。
如果你把作业的尺寸增加一倍,事情应该会更好。
此外,没有理由检查total > maxElements
。这根本没有必要。
我怀疑Airport类的复制构造函数有错误。您需要为Airport定义一个复制构造函数(对其数据进行深度复制),并重载赋值运算符以使用新的复制构造函数。否则,当执行resized[i] = orig[i];
时,将执行浅层复制,该复制最终仍指向原始(现已删除)Airport对象中的数据。
看看这里:http://www.cplusplus.com/articles/y8hv0pDG/
相关文章:
- 将动态分配的数组的大小调整为较小的大小C++
- 我的C++程序有问题.涉及动态调整整数数组的大小
- 通过新的后传递后创建的动态数组的错误以调整函数
- 根据内容动态调整 qwidget 和 qlayout 的大小
- Qt:如何调整QGraphicsItem以动态更改大小
- 调整动态数组大小时保留用户输入的值的问题
- C++我需要能够调整动态数组的大小
- 动态调整大小并填充C++中的矢量
- C++调整动态数组的大小
- 如何在C++中实现可动态调整大小的堆栈
- 在微控制器上用C++调整动态数组的大小是个好主意吗
- C++如何在不丢失数据的情况下调整动态数组的大小
- 调整动态数组大小时内存泄漏
- 调整动态字符串的大小会导致内存泄漏
- C++ - 调整动态数组的大小
- 使用 ASSERT " _BLOCK_TYPE_IS_VALID(pHead->nBlockUse) "调整动态分配的内存C++的大小
- 调整动态字符串数组的大小
- 为类调整动态分配的指针数组的大小
- 调整动态数组 c++ 的大小
- 如何调整动态模板数组的大小