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

Dynamic resizing of an array in C++

本文关键字:调整 动态 数组 C++      更新时间:2023-10-16

我有一个类,其中包含指向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/