Re: overloading [] operator for matrix?
From: Cy Edmunds (cedmunds_at_spamless.rochester.rr.com)
Date: 02/28/04
- Next message: Ivan Vecerina: "Re: How to design GUI with wxwindow [OT]"
- Previous message: Mike Wahler: "Re: [OT] How to design GUI with wxwindow"
- In reply to: Dave: "overloading [] operator for matrix?"
- Next in thread: John Harrison: "Re: overloading [] operator for matrix?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Sat, 28 Feb 2004 05:45:28 GMT
"Dave" <davis_eric@yahoo.com> wrote in message
news:99f6e996.0402272108.60879104@posting.google.com...
> Hi there:
>
> i am doing a matrix class for practice. everything is ok except the []
> operator. Basically, i want to achieve the same way as the normal
> double[]'s, such as:
> m[2][3] = 4.0;
> m[3][4] = m[4][5] + m[2][3];
> cout<<m[2][3]<<endl;
> I also want the indices to be 1 based instead of 0 based.
>
> One way I can think out is to have the following overloaded operator
> in matrix class:
> double* operator [] (int row_index); suppose the matrix contains
> doubles and i am using a double pointer to store the numbers.
>
> but I have the following problems with this approach:
> 1. the second index can't be 1 based since it's used to directly
> indexed into the double*. It has to be 0 based.
Why? Can't you make the pointer point one location before the actual data?
We did it for years in Fortran. Of course there is some inefficiency with
computing the offset, but that's 1-based indexing for you.
> 2. it's not safe. since the function returns the row pointer. the
> caller can just call m[2] and then do some bad things.
Don't look now but indexing isn't safe. It's just pointer arithmetic in
disguise.
>
> but that's the only way I can think out now. Is there a good way to
> solve this problem?
You could have your operator [] return a "row" class representing a row in
your matrix. There might be some advantage to this for implementing
operations such as row swapping. However it's not going to be more efficient
for indexing than just returning a pointer and may be considerably less so.
>
> Thanks a lot.
-- Cy http://home.rochester.rr.com/cyhome/
- Next message: Ivan Vecerina: "Re: How to design GUI with wxwindow [OT]"
- Previous message: Mike Wahler: "Re: [OT] How to design GUI with wxwindow"
- In reply to: Dave: "overloading [] operator for matrix?"
- Next in thread: John Harrison: "Re: overloading [] operator for matrix?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|