View Single Post
Old 01-31-2005, 02:07 PM   #3 (permalink)
Valmont
[code][/code] enforcer
 
Valmont's Avatar
 
Join Date: Mar 2003
Location: Netherlands
Posts: 1,544
Valmont is on a distinguished road
Why not making your life easier?
Code:
#ifndef C2DMATRIX_H
#define C2DMATRIX_H

#include <vector>
#include <string>
#include <iostream>
#include <stdexcept>

using namespace std;

class C2DMatrixError
{
public:
  C2DMatrixError(std::string msg) : sMsg_(msg)
    {}
  virtual std::string what() = 0;
protected:
  std::string sMsg_;
};

//--

class BadSize : public C2DMatrixError
{
public:
  BadSize(std::string msg) : C2DMatrixError(msg)
    {}
  std::string what()
  {
    return sMsg_;
  } 
};

//--

class BoundsViolation : public C2DMatrixError
{
public:
  BoundsViolation(std::string msg) : C2DMatrixError(msg)
    {}
  std::string what()
  {    
    return sMsg_;
  }
};

//--

template<typename T>
class C2DMatrix 
{
public:
  C2DMatrix() {}
  C2DMatrix(unsigned, unsigned );
  
  T& operator() (unsigned, unsigned);
  const T& operator() (unsigned i, unsigned j) const;   
   size_t nRows_;
   size_t nCols_;
private:
  vector<vector<T> > data_;
  template <typename _T>
  friend ostream& operator<<(ostream&  os, C2DMatrix<_T>& c2d );
};

//---------------------------
 
template<typename T>
C2DMatrix<T>::C2DMatrix(unsigned rows, unsigned cols)  
{
  if (rows == 0 || cols == 0)
  {
    throw BadSize("ERROR: Bad size");
  }
  data_.resize(rows);
  nRows_=rows;
  nCols_=cols;
  for (unsigned i = 0; i < rows; ++i)
  {
    data_[i].resize(cols);
  }
}
 
//----------------------------

template<typename T>
inline T& C2DMatrix<T>::operator() (unsigned row, unsigned col)
{
  if (row >= nRows_ || col >= nCols_ ) 
  {
    throw BoundsViolation("ERROR in non-const operator(): Bounds Violation");
  }
  return data_[row][col];
} 
 
//----------------------------

template<typename T>
inline const T& C2DMatrix<T>::operator() (unsigned row, unsigned col) const
{
  if (row >= nRows_ || col >= nCols_)
  {
    throw BoundsViolation("ERROR in const operator()const: Bounds Violation");
  }
  return data_[row][col];
}
 
//-----------------------------

template <typename T>
ostream& operator<< (ostream&  os, C2DMatrix<T>& c2d)
{
  for (int i=0; i < c2d.nRows_; i++)
  {
    for (int j=0; j < c2d.nCols_; j++)
    {
      os << c2d(i,j) << " ";
    }
    os << endl;
  }
  return os; 
}

#endif //C2DMATRIX_H
Code:
#include "C2DArray.h"
#include <iostream>
#include <cstdlib>
#include <vector>

using namespace std;

class object 
{
public:
  object() : array(C2DMatrix<int>(1,1))
  { }
  C2DMatrix<int> array;
};

int main()
{
  try
  {
    object start;
    cout<<start.array<<endl;  
    start.array(1,1)=1;
    cout<<start.array<<endl;
  }
  catch(C2DMatrixError& err)
  {
    cout<<err.what()<<endl;
  }
    
  return 0;
}
__________________
Valmont is offline   Reply With Quote