Department of Computer Science | Institute of Theoretical Computer Science | CADMO

Theory of Combinatorial Algorithms

Prof. Emo Welzl and Prof. Bernd Gärtner

// Prog: array.C // implement a class for variable-length arrays. // class array: definition class array { public: typedef bool T; // --- Constructor from int --------------------------- // PRE: n >= 0 // POST: *this is initialized with an array of length n array (int n); // --- Copy Constructor ------------------------------- // POST: *this is initialized from a array (const array& a); // --- Assignment Operator ---------------------------- // POST: a is assigned to *this; the new value of *this // is returned as an lvalue array& operator= (const array& a); // --- Destructor ------------------------------------- ~array (); // --- Index operator (non-const) --------------------- // PRE: the array has length at least i // POST: return value is i-th element (as reference) T& operator[] (int i); // --- Index operator (const) ------------------------- // PRE: the array has length at least i // POST: return value is i-th element (as a copy) const T& operator[] (int i) const; private: T* ptr; // pointer to first element int size; // number of elements }; // class array: implementation array::array (int n) : ptr (new T[n]), size (n) {} array::array (const array& a) : ptr (new T[a.size]), size (a.size) { // now copy the elements of a into *this for (int i = 0; i < size; ++i) ptr[i] = a[i]; } array& array::operator= (const array& a) { // avoid self-assignments if (this != &a) { // free memory of old value and get new memory // for new value delete[] ptr; ptr = new T[size = a.size]; // copy the elements of a into *this for (int i = 0; i < size; ++i) ptr[i] = a[i]; } return *this; } array::~array () { delete[] ptr; } array::T& array::operator[] (int i) { return ptr[i]; } const array::T& array::operator[] (int i) const { return ptr[i]; }