I need to add elements to a dynamically allocated Flight
array to my program. 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.
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
. 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. 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.
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.