[英]How do I when to extend a dynamically allocated array?
I need to add elements to a dynamically allocated Flight
array to my program.我需要将元素添加到我的程序的动态分配的
Flight
数组中。 As initialization of the Flight* allFlights
, I set the size of the array as 1 and want to enlarge its size as I need to add more.作为
Flight* allFlights
初始化,我将数组的大小设置为 1 并希望扩大其大小,因为我需要添加更多。
Such as:如:
//Flight.cpp
Flight::Flight(int flightNumber, int rowNumber, int seatNumber)
{
flightNo = flightNumber;
rowNo = rowNumber;
seatNo = seatNumber;
}
//main.cpp
Flight* allFlights = new Flight[1];
I could not find a proper way to extend it as needed, so I tried to approach the problem by having 2 separate integer values as numberOfFlights
and capacityOfFlights
.我找不到根据需要扩展它的正确方法,所以我试图通过将 2 个单独的整数值作为
numberOfFlights
和capacityOfFlights
来解决这个问题。 I initialized numberOfFlights
as 0 and capacityOfFlights
to 1, and incremented numberOfFlights
by 1 each time I added a new Flight
and compared it to capacityOfFlights
at each addition.我将
numberOfFlights
初始化为 0,将capacityOfFlights
初始化为 1,并在每次添加新Flight
时将numberOfFlights
增加 1,并在每次添加时将其与capacityOfFlights
进行比较。 If they were equal, I followed the steps below to extend my array.如果它们相等,我按照以下步骤扩展我的阵列。
if (numberOfFlights != flightCapacity)
{
Flight newFlight(flightNo, rowNo, seatNo); //Creating new flight object
allFlights[numberOfFlights] = newFlight;
numberOfFlights = numberOfFlights + 1;
}
else
{
Flight newFlight(flightNo, rowNo, seatNo); //Creating new flight object
//Reallocating dynamic array of allFlight to fit new flights
flightCapacity = flightCapacity * 2;
auto* temp = new Flight[flightCapacity];
copy(allFlights, allFlights + numberOfFlights, temp);
delete[] allFlights;
allFlights = temp;
//Adding the new flight to array
allFlights[numberOfFlights] = newFlight;
numberOfFlights = numberOfFlights + 1;
}
I know using std::vector
could easily solve this problem, but in this case I'm not allowed to use it.我知道使用
std::vector
可以轻松解决这个问题,但在这种情况下我不允许使用它。
Is this a good way to solve the problem?这是解决问题的好方法吗? I personally find it wasteful of resources by using 2
int
values and constantly checking the size by if
statements.我个人认为使用 2 个
int
值并通过if
语句不断检查大小会浪费资源。
Your code have duplicate parts.您的代码有重复的部分。 Increasing of array and putting data there can be separated.
增加数组和放置数据是可以分开的。
if (numberOfFlights == flightCapacity)
{
//Reallocating dynamic array of allFlight to fit new flights
flightCapacity = flightCapacity * 2;
auto* temp = new Flight[flightCapacity];
copy(allFlights, allFlights + numberOfFlights, temp);
delete[] allFlights;
allFlights = temp;
}
Flight newFlight(flightNo, rowNo, seatNo); //Creating new flight object
//Adding the new flight to array
allFlights[numberOfFlights] = newFlight;
numberOfFlights = numberOfFlights + 1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.