1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
|
//#define DEBUG_GRIMATRIX // debug
// Store items in a matrix. Items can be builtins or classes.
#if !defined(_GMatrix_h_)
#define _GMatrix_h_
template<class T>
class GriMatrix
{
public:
GriMatrix();
~GriMatrix();
void set_size(unsigned int num_cols, unsigned int num_rows);
void set_value(T value);
T& operator()(unsigned int col, unsigned int row);
T operator()(unsigned int col, unsigned int row) const;
protected:
int haveData;
unsigned int rows; // row < rows
unsigned int cols; // col < cols
T *contents;
void err(const char *msg) const;
};
template<class T>
GriMatrix<T>::GriMatrix()
{
haveData = rows = cols = 0;
}
template<class T>
GriMatrix<T>::~GriMatrix()
{
if (haveData)
delete [] contents;
}
template<class T>
void GriMatrix<T>::set_size(unsigned int num_cols, unsigned int num_rows)
{
if (num_rows == 0 && num_cols == 0) {
if (haveData)
delete [] contents;
haveData = rows = cols = 0;
} else {
if (haveData)
delete [] contents;
rows = num_rows;
cols = num_cols;
contents = new T[rows * cols];
if (!contents)
err("Out of memory (GriMatrix)");
haveData = 1;
#ifdef DEBUG_GRIMATRIX
printf("GriMatrix.set_size(rows=%d,cols=%d) start=%lx end=%lx\n",rows,cols,contents,contents + cols * rows - 1);
#endif
}
}
template<class T>
void GriMatrix<T>::set_value(T value)
{
for (unsigned int col = 0; col < cols; col++)
for (unsigned int row = 0; row < rows; row++)
contents[row + col * rows] = value;
}
template<class T>
T& GriMatrix<T>::operator()(unsigned int col, unsigned int row)
{
if (!haveData)
err("Trying to get data from empty GriMatrix");
char errorMsg[100];
if (row > rows - 1) {
sprintf(errorMsg, "\
Can't use row %d of matrix; valid range: 0-%d", row, rows-1);
err(errorMsg);
}
if (col > cols - 1) {
sprintf(errorMsg, "\
Can't use col %d of matrix; valid range: 0-%d", col, cols-1);
err(errorMsg);
}
return contents[row + col * rows];
}
template<class T>
T GriMatrix<T>::operator()(unsigned int col, unsigned int row) const
{
if (!haveData)
err("Trying to get data from empty GriMatrix");
char errorMsg[100];
if (row > rows - 1) {
sprintf(errorMsg, "\
Can't use row %d of matrix; valid range: 0-%d", row, rows-1);
err(errorMsg);
}
if (col > cols - 1) {
sprintf(errorMsg, "\
Can't use col %d of matrix; valid range: 0-%d", col, cols-1);
err(errorMsg);
}
return contents[row + col * rows];
}
template<class T>
void GriMatrix<T>::err(const char *msg) const
{
gr_Error(msg);
}
#endif // _GMatrix_h_
|