Path: utzoo!attcan!uunet!snorkelwacker!think!gem.mps.ohio-state.edu!mips!excelan!sjsumcs!horstman From: horstman@sjsumcs.sjsu.edu (Cay Horstmann) Newsgroups: comp.lang.c++ Subject: Re: operator[] for 2D array class Summary: Double operator[] can be achieved by having the first one return X* Message-ID: <1989Nov21.034439.27095@sjsumcs.sjsu.edu> Date: 21 Nov 89 03:44:39 GMT Expires: 12/15/89 References: <21162@ut-emx.UUCP> Reply-To: horstman@sjsumcs.SJSU.EDU (Cay Horstmann) Organization: San Jose State University Lines: 44 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