>
> On Fri, May 25, 2007 at 07:49:53PM -0600, Von Fugal wrote:
> > Random thought on this dynamic multidimensional array stuff:
> >
> > int **new_array(int rows, int cols) {
> > int size = (cols + 1) * rows;
> > int **ary = new int* [size];
> > int **i = ary;
> > while (i < ary + size) {
> > ary[i] = i + 1;
> > i += cols + 1;
> > }
> > return ary;
> > }
>
> What in the ... ??!!
>
>
My only objection is that it relies on the fact that an int and int* can be
readily interchanged. That's true on 32-bit x86 systems, but it will cut
down on your portability, so it's not something I'd recommend.
I think I'd go with something like this:
template<class T>
class Matrix {
int rows;
int cols;
T* data;
class MatrixHelper {
Matrix<T>& ref;
int row;
public:
MatrixHelper(Matrix<T>& m, int r) : ref(m), row(r) {}
inline T& operator[] (int c) { return ref.data[row*ref.cols + c]; }
};
public:
Matrix(int r, int c) : rows(r), cols(c) { data = new T[rows*cols]; }
~Matrix() { delete data; }
inline MatrixHelper operator[] (int r) { return MatrixHelper(*this, r);
}
};
I haven't run that through a compiler, so no promises. :) You do get the
advantages of a contiguous block of memory and not having to do a series of
new/deletes. It should also be fairly friendly to your compiler's
optimizer.
-Jared
--------------------
BYU Unix Users Group
http://uug.byu.edu/
The opinions expressed in this message are the responsibility of their
author. They are not endorsed by BYU, the BYU CS Department or BYU-UUG.
___________________________________________________________________
List Info: http://uug.byu.edu/cgi-bin/mailman/listinfo/uug-list