patterncppMinor
Simplifying a Resizing Method
Viewed 0 times
resizingsimplifyingmethod
Problem
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) 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.
}Solution
void Rebuild(std::size_t NewSize, bool FromFront = false)
{
const std::size_t OldSize = Size;
Datatype* NewStorage = new Datatype[NewSize];Rather then creating a temporary array and copying the existing data into it, just create the new array and copy into that.
int CopyLength = std::min(OldSize, NewSize);We start by determining how many elements we will actually copy
if( FromFront )
{
std::copy(BasePointer + OldSize - CopyLength, BasePointer + OldSize,
NewStorage + NewSize - CopyLength);
}
else
{
std::copy(BasePointer, BasePointer + CopyLength, NewStorage);
}I use std::copy to avoid having to write a copying for loop myself.
delete[] BasePointer; // Delete the main array...
BasePointer = NewStorage;
Size = NewSize; // Size is used in other methods.delete the current array and replace it with my new array
}Code Snippets
void Rebuild(std::size_t NewSize, bool FromFront = false)
{
const std::size_t OldSize = Size;
Datatype* NewStorage = new Datatype[NewSize];int CopyLength = std::min(OldSize, NewSize);if( FromFront )
{
std::copy(BasePointer + OldSize - CopyLength, BasePointer + OldSize,
NewStorage + NewSize - CopyLength);
}
else
{
std::copy(BasePointer, BasePointer + CopyLength, NewStorage);
}delete[] BasePointer; // Delete the main array...
BasePointer = NewStorage;
Size = NewSize; // Size is used in other methods.Context
StackExchange Code Review Q#1252, answer score: 9
Revisions (0)
No revisions yet.