#ifndef _ARRAY_CC #define _ARRAY_CC #include #include #include "Array.h" #include "test_utilities.h" // destructor template Array::~Array() { if (table) delete[] table; } // constructor without default template Array::Array() { use_default = 0; table_size = 0; max_referenced = -1; table = NULL; } // constructor with default template Array::Array(const VALUE& def) { use_default = 1; default_init = def; table_size = 0; max_referenced = -1; table = NULL; } // copy constructor -- defined in Array.h // clear template void Array::clear() { if (table) { delete[] table; table_size = 0; max_referenced = -1; table = NULL; } } // copy function template void Array::copy(const Array & a) { if (&a == this) return; clear(); use_default = a.use_default; default_init = a.default_init; max_referenced = a.max_referenced; table_size = a.table_size; if (a.table) { table = new VALUE[table_size]; if (!table) { die("Out of memory"); } for (int i = 0; i < table_size; ++i) table[i] = a.table[i]; } } // grow template void Array::grow() { int new_size = 2 * table_size; if (table == NULL) new_size = 3; VALUE *new_table = new VALUE[new_size]; if (! new_table) { die("Out of memory"); } int i; for (i = 0; i < table_size; ++i) new_table[i] = table[i]; if (use_default) for ( ; i < new_size; ++i) new_table[i] = default_init; if (table) delete[] table; table = new_table; table_size = new_size; } // operator[] template VALUE & Array::operator[](int index) { if (index < 0) die("Negative index"); while (index >= table_size) grow(); if (index > max_referenced) max_referenced = index; return table[index]; } // operator[] const template VALUE Array::operator[](int index) const { if (index > max_referenced) die("Array index out of bounds (index = " << index << ", max_referenced = " << max_referenced << ")"); if (index < 0) die("Negative index"); return table[index]; } // size template int Array::size() const { return max_referenced+1; } // print template std::ostream & operator<<(std::ostream & out, const Array & a) { out << "["; for (int i = 0; i < a.size(); ++i) { if (i != 0) out << ", "; out << a[i]; } out << "]"; return out; } #endif