[   ^ to index...   |   <-- previous   |   next -->   ]

Vector: an alternative implementation

What if we wanted to make the Vector size itself dynamically on demand? We would have to allocate an array of memory whose size is determined at runtime.

new, delete, delete []

The new operator will attempt to allocate on the heap a new object or array of the requested type. A new expression returns a pointer to the newly allocated object:

Item * i = new Item; // Allocate & construct an Item Item * iarr = new Item[50]; // Allocate & construct 50 Items

If the allocation fails, new will return null. Always check for allocation failures:

if (!i) { cerr << "Error: could not allocate memory." }

Heap-allocated memory persists forever, until you release it or the program exits. In this way, it resembles open file handles or any other persistent resource. Not releasing allocated memory will result in a memory leak.

delete i; // Single object delete delete [] iarr; // Array delete

Dynamically sized vector

class Vector { // ... private: int maxSize; int length; Item * items; }; Vector::Vector() { maxSize = 16; items = new Item[maxSize]; length = 0; } void Vector::insert(int position, Item item) { assert(position >= 0 && position <= length); if (length == maxSize) { // What goes here? (about 7 lines of code) } for (int i=length; i>position; i--) items[i] = items[i-1]; items[position] = item; ++length; } Solution...


Last modified: Thu Jul 6 13:52:47 PDT 2000