Suppose you have an array, items, with capacity 5 and suppose also you have a count varaible that counts each entry added to the array. How would you realloacte the array? Using C++ syntax?
void BST::reallocate()
{
item *new_array = new item[size*2];
for ( int array_index = 0; array_index < size * 2; array_index++ )
{
if ( ! items[array_index].empty )
{
new_array[array_index].theData = items[array_index].theData;
开发者_C百科 new_array[array_index].empty = false;
}
}
maxSize += size;
delete [] items;
items = NULL;
items = new_array;
}
How do you reallocate an array? BST ctor is below with the private items struct, just to eliminate any confusion.
BST::BST(int capacity) : items(new item[capacity]), Position(0),
leftChild(0), rightChild(0), maxSize(capacity)
{
}
this is in the BST header:
private:
int size;
int maxSize;
int Position;
int leftChild;
int rightChild;
struct item
{
bool empty;
data theData;
};
item *items;
The quesetion is that i seem to be having a hard time with the reallocation of my items array.
I would reallocate it in the form of a std::vector<item>
, assuming that there is no overriding reason to use an array. That would avoid several problems completely.
Why are you doing this at all? Why do you think that:
std::vector<item> items;
won't work for you?
Your old array items
has only size
elements, so you need to change the upper limit in your for
loop to size
from size*2
when you're copying the old elements to the new array.
Maybe because size is not initialized. Also, you would need to make sure size is less than maxSize.
精彩评论