gpt4 book ai didi

c++ - C++中数组的动态调整大小

转载 作者:行者123 更新时间:2023-11-28 00:04:28 25 4
gpt4 key购买 nike

我有一个包含指向 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

如果你将 doublesize 上移到分配之上,事情应该会更好。

此外,没有理由检查 total > maxElements。根本没有必要。

关于c++ - C++中数组的动态调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36537835/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com