/* ** $Id: simplearray,v 1.1 2003/01/27 15:36:32 phf Exp $ ** ** Copyright (c) 2003 by Peter H. Froehlich . ** Freely distributable for educational purposes. */ #ifndef _CS14_SIMPLEARRAY #define _CS14_SIMPLEARRAY #include #include "array.h" namespace cs14 { template class SimpleArray: public Array { // The C++ array used to represent our storage. T *rep; // The length of our array. int len; // Helper to allocate memory, len needs to be set. void create() { rep = new T[len]; } // Helper to free memory. void destroy() { delete[] rep; } // Helper to copy the C++ array, rep needs to be set. void copy( const SimpleArray &that ) { for (int i = 0; i < that.len; i++) { rep[i] = that.rep[i]; } } public: SimpleArray( int length, T initial ) throw (std::domain_error): rep(NULL), len(0) { if ( 0 < length ) { len = length; create(); for (int i = 0; i < len; i++) { rep[i] = initial; } } else { throw std::domain_error( "new: 0 < length violated!" ); } } SimpleArray( const SimpleArray &that ): cs14::Array(), rep(NULL), len(0) { len = that.len; create(); copy( that ); } virtual ~SimpleArray() { destroy(); rep = NULL; len = 0; } SimpleArray& operator=( const SimpleArray &that ) { if ( this != &that ) { destroy(); len = that.len; create(); copy( that ); } return *this; } const T& operator[]( int index ) const throw (std::out_of_range) { if ( (0 <= index) and (index < length()) ) { return rep[index]; } else { throw std::out_of_range( "[]: get context out of range!" ); } } T& operator[]( int index ) throw (std::out_of_range) { if ( (0 <= index) and (index < length()) ) { return rep[index]; } else { throw std::out_of_range( "[]: put context out of range!" ); } } T get( int index ) const throw (std::out_of_range) { if ( (0 <= index) and (index < length()) ) { return rep[index]; } else { throw std::out_of_range( "get: index out of range!" ); } } void put( int index, T t ) throw (std::out_of_range) { if ( (0 <= index) and (index < length()) ) { rep[index] = t; } else { throw std::out_of_range( "put: index out of range!" ); } } int length() const { return len; } }; } // namespace cs14 #endif /* _CS14_SIMPLEARRAY */