/* * Dynamically allocated two dimensional array as a class. * Operators are defined to allow it be treated just like * a variable declared as a regular two dimensional array. * Assignment between these objects is also supported. * The underlying storage is a single dimensional array, * and the row calculation is done by the array operator. */ #ifndef _ARRAY_2D_H_ #define _ARRAY_2D_H_ #include #include using namespace std; template class Array2d { public: // Constructors Array2d(int rows, int cols) : _rows(rows), _cols(cols) { _data = new T[_rows * _cols]; } Array2d(const Array2d & exist); ~Array2d() { delete [] _data; } // Assignment of arrays Array2d & operator = (const Array2d & rhs); // The array operator - note a T pointer is returned, // so this behaves just like native 2d arrays T * operator [] (int i) { return &_data[cols() * i]; } const T * operator [] (int i) const { return &_data[cols() * i]; } // Transpose an array Array2d transpose() const; int rows() const { return _rows; } int cols() const { return _cols; } private: // Private utility for copying void copy(const Array2d & exist); T *_data; int _rows; int _cols; }; // Print an array template ostream & operator << (ostream &, const Array2d &); #include "Array2d.c" #endif