Introduction
Sometimes, we have a need of class behaving C-like 2-dimension array x[i][j]
. For my own professional usage, I tried to find on the net a code snippet that I can adapt for my situation.
Unfortunately, all I've got are one dimension. By this tip, I propose a simple manner to have this class.
Background
We generally manage one dimension by overloading operator []
and expose 2 methods, one in lvalue
and one other in rvalue
. Here is a simple program for that.
class C1D
{
int* _array;
public:
C1D(int n)
{
_array = new int[n];
}
const int operator[] (int index) const
{
return _array[index];
}
int& operator[] (int index)
{
return _array[index];
}
};
Using the Code
As you can see, I use a GETTER who returns a constant value, it allows me to not use it as an lvalue
.
Now we can get a value for a particular index 1
and assign a value like this:
C1D o1D(3);
<span style="font-size: 9pt;">o1D[1] = 3;
</span><span style="font-size: 9pt;">int val = o1D[1]; </span>
How To Deal With 2 Dimensions Now?
Suppose we need a class that implements an array of points like this CPoint**
. We must use an intermediate class CRow
implementing CPoint*
according to this code.
class C2D
{
CPoint** m_points;
public:
class CRow
{
CPoint* m_pPoints;
public:
CRow(CPoint* pPoints): m_pPoints(pPoints){}
};
const CRow operator [](unsigned int x) const
{
return CRow(m_points[x]);
}
CPoint* operator [](unsigned int x)
{
return m_points[x];
}
};
Points of Interest
Our GETTER method returns an object of CRow
which guards a pointer to a class CPoint
. It remains to us to write getter and setter method for our class CRow
like we've done for C1D
.
The definitive code for our 2-dimensional class is:
class CPoint
{
public:
int m_x, m_y, m_val;
CPoint(unsigned int x = 0, unsigned int y = 0)
: m_x(x), m_y(y), m_val(x + y)
{}
CPoint& operator=(const CPoint& op)
{
m_x = op.m_x;
m_y = op.m_y;
m_val = op.m_val;
return *this;
}
CPoint& operator=(int val)
{
m_val = val;
return *this;
}
};
class C2D
{
CPoint** m_points;
public:
unsigned int m_w, m_h;
C2D():m_w(10), m_h(20)
{
m_points = new CPoint*[m_h];
for(unsigned int i = 0 ; i < m_h ; i++ ) {
m_points[i] = new CPoint[m_w];
}
}
C2D(unsigned int w, unsigned int h):m_w(w), m_h(h){}
string getSize()
{
ostringstream oss;
oss << "Width : " << m_w << ", height : " << m_h;
return string(oss.str());
}
class CRow
{
CPoint* m_pPoints;
public:
CRow(){}
CRow(CPoint* pPoints){ m_pPoints = pPoints; }
const CPoint operator[](int index) const
{
return m_pPoints[index];
}
CPoint& operator[](int index)
{
return m_pPoints[index];
}
};
const CRow operator [](unsigned int x) const
{
return CRow(m_points[x]);
}
CPoint* operator [](unsigned int x)
{
return m_points[x];
}
};
History
- 5th October, 2015: Initial version