I'm making a simple container class for fun and education, but my rebuilding/resizing method seems rather inefficient. Is there an easier way to do this?
// If FromFront is true, cells should be added or
// subtracted from the front of the array rather than the back.
void Rebuild(std::size_t NewSize, bool FromFront = false)
{
const std::size_t OldSize = Size;
Size = NewSize; // Size is used in other methods.
Datatype* TemporaryStorage = new Datatype[OldSize]; // Allocate space for the values to be preserved while a new main array is made.
for (std::size_t Index = 0; Index < OldSize; Index++) TemporaryStorage[Index] = BasePointer[Index]; // Copy values over to the temporary array.
delete[] BasePointer; // Delete the main array...
BasePointer = new Datatype[NewSize]; // ...And rebuild it with the appropriate size.
for (std::size_t Iteration = 0; (Iteration < OldSize) && (Iteration < NewSize); Iteration++)
{
std::size_t BasePointerIndex = Iteration;
std::size_t TemporaryStorageIndex = Iteration;
if (FromFront) // We need to take special measures to give the indices offsets.
{
if (NewSize > OldSize) BasePointerIndex += (NewSize - OldSize);
else TemporaryStorageIndex += (OldSize - NewSize);
}
BasePointer[BasePointerIndex] = TemporaryStorage[TemporaryStorageIndex]; // Copy values from the temporary array to the new main array.
}
delete[] TemporaryStorage; // Finally, delete the temporary storage array.
}