subscript operator overloading

U

Uday

hello friends,
i have defined a template two dimensional array. its working
fine. since the operator[] function gives me only the row index, i
couldn't catch the column index overflow. is there any way to find &
check it wothout using operator()(int row, int column) function?

Uday.
 
O

Oliver Kreylos

Uday said:
i have defined a template two dimensional array. its working
fine. since the operator[] function gives me only the row index, i
couldn't catch the column index overflow. is there any way to find &
check it wothout using operator()(int row, int column) function?

Interesting problem. One solution I could think of is have the
operator[] of the 2D array return not a pointer to the selected row (and
use the standard C operator[] for pointers to the column dereferencing),
but have it return a special temporary object that represents the
column, and has another overloaded operator[] to do range checking and
dereferencing. C++ compilers should be able to optimize away most -- if
not all -- the overhead inherent in creating/returning a temporary.

Hope this helps,

Oliver
 
Joined
Aug 23, 2007
Messages
1
Reaction score
0
reply

If you really need Object[y][x] you may use an indirection to the object.

For instance
Code:
class Item {
  int onedim[100];
public:
  int &operator[] (int x) { return(onedim[x]); }
};

Item twodim[20];
Then to access your data
Code:
for (int j=0 ; j<20 ; j++) for (int i=0 ; i<100 ; i++) twodim[j][i] = i*j;
You may also use a vector<Item> instead of Item twodim[..]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,201
Messages
2,571,052
Members
47,656
Latest member
rickwatson

Latest Threads

Top