[comp.lang.c++] operator[] for 2D array class

ycy@walt.cc.utexas.edu (Joseph Yip) (11/19/89)

I am working on some routines that manipulate 2D array. In order to
access individual elements, I define a operator [] member function.
However, operator [] only takes one parameter. In order to do

	A[i][j] = B[i][j]	// A and B are two 2D array classes

I do:

Tmp Array2D::operator [] (int i) {
	...
}

int& Tmp::operator[] (int j) {
	...
}

In this way, the problem is solved. 

Is there any better way to do this object array indexing?

Thanks

Joseph 

horstman@sjsumcs.sjsu.edu (Cay Horstmann) (11/21/89)

In article <21162@ut-emx.UUCP> ycy@walt.cc.utexas.edu (Joseph Yip) writes:
>I am working on some routines that manipulate 2D array. In order to
>access individual elements, I define a operator [] member function.
>However, operator [] only takes one parameter. In order to do
>
>	A[i][j] = B[i][j]	// A and B are two 2D array classes
>
>I do:
>
>Tmp Array2D::operator [] (int i) {
>	...
>}
>
>int& Tmp::operator[] (int j) {
>	...
>}
>
>In this way, the problem is solved. 
>
>Is there any better way to do this object array indexing?
>

It depends. If your Array2D class internally stores all elements of a
given row consecutively somewhere, then you can have operator[] return a 
pointer to that row. Here is a naive example of a 2-dimensional array of X's

class Array2D
{	int rows, cols;
	X* elem;
	Array2D( r, c ) { rows = r; cols = c; elem = new X[r*c]; }
	X* operator[]( int n ) { if( 0 <= n && n < r ) return elem+n*cols; }
	~Array2D() { delete elem; }
};

Array2D a(3,3); 
a[1][2] = x;

a[1] returns a.elem + 1*3, a pointer to the first row of a, i.e. it skips
past the 0th row. The [2] is simply C-style [], namely *(a[1] + 2).

The trick is to return an X* so that the second [] becomes the C-style [].
Of course, this trick fails for triangular, bidiagonal or other sparse matrices.

Cay

turk@Apple.COM (Ken "Turk" Turkowski) (12/20/89)

In article <21162@ut-emx.UUCP> ycy@walt.cc.utexas.edu (Joseph Yip) writes:
>I am working on some routines that manipulate 2D array. In order to
>access individual elements, I define a operator [] member function.
>However, operator [] only takes one parameter. In order to do
>	A[i][j] = B[i][j]	// A and B are two 2D array classes
>I do:
>Tmp Array2D::operator [] (int i) {
>	...
>}
>
>int& Tmp::operator[] (int j) {
>	...
>}
>
>In this way, the problem is solved. 
>Is there any better way to do this object array indexing?
Yes; e.g.

	class 2DarrayOfElements {
	private:
		int nCols;
		element *M;
	public:
		element* operator [] (int i) { return(M + i * nCols); }
	};

-- 
Ken Turkowski @ Apple Computer, Inc., Cupertino, CA
Internet: turk@apple.com
Applelink: TURKOWSKI1
UUCP: sun!apple!turk