/* * File: array.tem * Author: Robert I. Pitts * Last Modified: Fall 2000 * Topic: Templates * ----------------------------------------------------- * * This is the implementation of a class representing a resizable array. * */ /* * Constructor * ------------------------- * The array should be initially empty, so we need not allocate any * space. We initialize the pointer and set the 'sz' (size) to zero. */ template Array::Array() { contents = NULL; sz = 0; } /* Destructor * ----------------------- * This deallocates all memory associated with the array. */ template Array::~Array() { delete [] contents; // Reset data, just in case. contents = NULL; sz = 0; } /* * Function: resize * ----------------------- * Make the array the requested size. If old size is larger * than new size, some elements will be lost. If the new * size is larger, the additional elements created will have * no initial value (unless elements have a default constructor). * We only use as much space as requested for the internal, * dynamically-allocated array, although we could be smarter * about allocation. Currently, it does not check to make * sure 'new_size' is valid. */ template void Array::resize(int new_size) { if (new_size != sz) { // New space Item *new_contents = new Item[new_size]; // Copy as much of old contents as needed for (int i = 0; i < sz && i < new_size; i++) { new_contents[i] = contents[i]; } delete contents; // Get rid of old array. contents = new_contents; sz = new_size; } } /* * Function: operator [] * ----------------------- * Allows access to a particular element in the array. * Currently, it does no range checking of the index. */ template Item &Array::operator [](int index) { return contents[index]; } /* * Function: size * ----------------------- * Returns the current size of the array. */ template int Array::size() const { return sz; }