C++ newbie: 2D array subscripting--problem passing array[i][j] AND array(i,j)...

Antst

New member
Joined
Jul 29, 2010
Messages
24
Reaction score
0
Points
1
...to function? Hi everyone:

I would be very grateful for some advice on a problem I'm having with 2-D array subscripting.

The problem is that some of my arrays are subscripted as array(i, j) (these were created in a class) and some are dynamic arrays subscripted as array[j]. I cannot pass both kinds of arrays as arguments to my functions.

Is there a fix for this? In the array class that produces array(i,j), I tried overloading my subscripting definition, but this did not work. In other words, I currently have:

T& operator ( ) ( int x, int y );
const T& operator( ) ( int x, int y ) const;

And I tried overloading by adding a second definition for []. This produced so many errors that I won't even try to write them all down here.

Does anyone know of a way to pass arrays as arguments to functions, where some of the arrays are subcripted as array[j] and some are array(i,j)?

Thank you very much for any help.
 
Overload a function. One that takes an normal array, and one that takes your class. If you want to overload a double [][] operator in your class, there is a way to do it. You give your class a data member that has operator [](like a normal array, or a vector). Then you overload the operator to return one of those. For example:

class Matrix
{
****vector<vector<int> > matrix_; // a vector of vectors of ints
public:
****Matrix(int x, int y) :matrix_(y) {
********for(int i=0; i<y; i++)
************matrix_.resize(x);
****}

****vector<int> & operator[](int index) { return matrix_[index]; }
};

int main()
{
****Matrix m(4,4);
****m[1][2] = 7;
}
 
Back
Top