Q: How can I define a dynamic two-dimensional array?
A: The following class shows one way of encapsulating a two-dimensional array:
Code:
template <class T>
class dynamic_2d_array
{
public:
dynamic_2d_array(int row, int col) : m_row(row),
m_col(col),
m_data((row != 0 && col != 0) ? new T[row * col] : NULL){}
dynamic_2d_array(const dynamic_2d_array& src) : m_row(src.m_row),
m_col(src.m_col),
m_data((src.m_row != 0 && src.m_col != 0) ? new T[src.m_row * src.m_col] : NULL)
{
for(int r = 0;r < m_row; ++r)
for(int c = 0; c < m_col; ++c)
(*this)[r][c] = src[r][c];
}
~dynamic_2d_array()
{
if(m_data)
delete []m_data;
}
inline T* operator[](int i) { return (m_data + (m_col * i)); }
inline T const*const operator[](int i) const {return (m_data + (m_col * i)); }
private:
dynamic_2d_array& operator=(const dynamic_2d_array&);
const int m_row;
const int m_col;
T* m_data;
};
A different approach using the STL 'vector' class is shown in the following FAQ...
FAQ contributed by: [Axter]