A wrapper for array classes to generate a two dimensional array



    
    #if !defined(TWO_DIM_H)
    #define TWO_DIM_H
    
    #if defined(__GNUG__)
    #  define PORT_NAMESPACE(space)
    #else
    #  define PORT_NAMESPACE(space) space::
    #endif

    
    #include <vector>
    #include <stdexcept>
    
    template <typename T, bool checked = true, typename Array = PORT_NAMESPACE(std) vector<T> >
    class two_dim_array
    {
    private:
      int const i_cols, i_rows;
      Array     i_array;        // Array has to be similar to 'vector' or 'deque'
    
    public:
      two_dim_array(int cols, int rows, T const &def = T()):
        i_cols(cols),
        i_rows(rows),
        i_array(cols * rows, def)
      {
      }
      // the compiler generated copy ctor, assignment operator, and dtor do
      // the right thing!
    
      friend class proxy
      {
        friend two_dim_array;
      private:
        two_dim_array &i_rep;
        int const     i_row_start;
      
        proxy(two_dim_array &rep, int row_start):
          i_rep(rep),
          i_row_start(row_start)
        {
        }
    
      public:
        T const &operator[](int col) const
        {
          if (checked && (col < 0 || i_rep.i_cols <= col))
    	throw PORT_NAMESPACE(std) out_of_range("Column index out of range");
          return i_rep.i_array[i_row_start + col];
        }
        T &operator[](int col)
        {
          if (checked && (col < 0 || i_rep.i_cols <= col))
    	throw PORT_NAMESPACE(std) out_of_range("Column index out of range");
          return i_rep.i_array[i_row_start + col];
        }
      };
    
      friend class const_proxy
      {
        friend two_dim_array;
      private:
        two_dim_array const &i_rep;
        int const           i_row_start;
      
        const_proxy(two_dim_array const &rep, int row_start):
          i_rep(rep),
          i_row_start(row_start)
        {
        }
    
      public:
        T const &operator[](int col) const
        {
          if (checked && (col < 0 || i_rep.i_cols <= col))
    	throw PORT_NAMESPACE(std) out_of_range("Column index out of range");
          return i_rep.i_array[i_row_start + col];
        }
      };
    
      const_proxy operator[](int row) const
      {
        if (checked && (row < 0 || i_rows <= row))
          throw PORT_NAMESPACE(std) out_of_range("Row index out of range");
        return const_proxy(*this, i_cols * row);
      }
      proxy operator[](int row)
      {
        if (checked && (row < 0 || i_rows <= row))
          throw PORT_NAMESPACE(std) out_of_range("Row index out of range");
        return proxy(*this, i_cols * row);
      }
    };

    
    #endif /* TWO_DIM_H */
    

Please send comments, suggestions, problem reports, bug fixes etc. to
Dietmar Kühl dietmar.kuehl@claas-solutions.de
This file is converted from C++ source to HTML using c++2html.