// -*- coding: utf-8 -*- // Time-stamp: // Representation of m×n arrays with an array for each line // // Repi Array of pointers Real arrays of T // +------------+ +-------------------+ // | Rep | +-------->| | | | .... | | // |+----------+| | +-------------------+ // || nlin || +--+ | +-------------------+ // |+----------+| | |--+ +----->| | | | .... | | // || ncol || +--+ | +-------------------+ // |+----------+| | |-----+ +-------------------+ // || refs || +--+ +-->| | | | .... | | // |+----------+| | |--------+ +-------------------+ // +------------+ +--+ +-------------------+ // | p |--------->| |----------->| | | | .... | | // +------------+ +--+ +-------------------+ #ifndef REPI_HPP #define REPI_HPP #include "rep.hpp" template class Repi : public Rep { public: // Constructor from dimensions Repi(int m, int n); // Assignment operator virtual typename Rep::Line operator[](int i) override; // Access operator to a constant array virtual const typename Rep::Line operator[](int i) const override; // Destructor ~Repi(); private: // Clone virtual Repi* clone() const override; // Array of pointers // Each p[i] contains a pointer to the array for line i. T** p; }; // Constructor from dimensions template Repi::Repi(int m, int n) : Rep(m, n) { #ifdef TRACE cout << "Repi(" << m << ", " << n << ") : " << this << endl; #endif // Alloc the array if both dimensions are positive if (this->nlin > 0 && this->ncol > 0) { // Alloc array for pointers to lines p = new T*[this->nlin]; for(int i = 0; i < this->nlin; i++) // Alloc each line p[i] = new T[this->ncol]; } else { // Mark no allocation has occurred p = nullptr; } } // Destructor template Repi::~Repi() { #ifdef TRACE cout << "~Repi() : " << this << endl; #endif // Free the array only if there is some if (p != nullptr) { for(int i = 0; i < this->nlin; i++) // Free each line if (p[i] != nullptr) delete [] p[i]; // Free array for pointers to lines delete [] p; } } // Clone template Repi* Repi::clone() const { // Create copy of representation Repi* tmp = new Repi(this->nlin, this->ncol); // Copy elements for(int i = 0; i < this->nlin; i++) for(int j = 0; j < this->ncol; j++) tmp->p[i][j] = p[i][j]; return tmp; // Return copy } // Access operator to a non-constant array template typename Rep::Line Repi::operator[](int i) { if (0 <= i && i < this->nlin) return typename Rep::Line(p[i], this->ncol); else throw new exception(); } // Access operator to a constant array template const typename Rep::Line Repi::operator[](int i) const { if (0 <= i && i < this->nlin) return typename Rep::Line(p[i], this->ncol); else throw new exception(); } #endif