Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overload array index operator for wrapper class of 2D array? [duplicate]

#define ROW 3
#define COL 4

class Matrix
{
   private:
      int mat[ROW][COL];  
    //.....
    //.....

};

int main()
{
  Matrix m;
  int a = m[0][1]; //  reading
  m[0][2] = m[1][1]; // writing
} 

I think directly it not possible to overload [][] .

I think i have to do it indirectly but how to implement it?

like image 852
Ashish Avatar asked Dec 28 '09 19:12

Ashish


2 Answers

The easier solution is to use the operator() as it allows multiple parameters.

class M
{
    public:
       int& operator()(int x,int y)  {return at(x,y);}
    // .. Stuff to hold data and implement at()
};


M   a;
a(1,2) = 4;

The easy way is that the first operator[] returns an intermediate object that the second operator[] returns the value from the array.

class M
{
    public:
    class R
    {
         private:
             friend class M; // Only M can create these objects.
             R(M& parent,int row): m_parent(parent),m_row(row) {}
         public:
              int& operator[](int col) {return m_parent.at(m_row,col);}
         private:
              M&  m_parent;
              int m_row;
    };

    R operator[](int row) {return R(*this,row);}

    // .. Stuff to hold data and implement at()
};

M   b;
b[1][2] = 3;   // This is shorthand for:

R    row = b[1];
int& val = row[2];
val      = 3;
like image 128
Martin York Avatar answered Nov 14 '22 23:11

Martin York


Since you want to store your elements in fixed-size arrays it'll be fairly easy:

#define ROWS 3
#define COLS 4

typedef int row_type[COLS];

class matrix {
   row_type elements[ROWS];
public:
   ...
   row_type const& operator[](int r) const {return elements[r];}
   row_type      & operator[](int r)       {return elements[r];}
   ...
};

That should work.

In addition, you may want to replace the #defines with proper constants or use template parameters for type (int) and size (3x4) to make your matrix class more generic. If you want to support dynamic sizes your operator[] needs to return proxy-objects. It's possible but you should probably prefer operator() with two index parameters for element access.

like image 31
sellibitze Avatar answered Nov 15 '22 00:11

sellibitze