#include <iostream>
#include <sstream>
using namespace std;
template <typename T>
class Matrix2D
{
private:
size_t m_rows, m_cols;
T *m_data;
size_t max_string_length() const;
public:
explicit Matrix2D();
explicit Matrix2D(size_t rows, size_t cols);
explicit Matrix2D(size_t rows, size_t cols, T initial_value);
Matrix2D(const Matrix2D<T>& m);
Matrix2D<T>& operator=(const Matrix2D<T>& m);
virtual ~Matrix2D()
{
delete [] m_data;
}
T &operator()(size_t row, size_t col);
T operator()(size_t row, size_t col) const;
template <typename _T>
friend ostream& operator<<(ostream& out, const Matrix2D<_T>& m);
size_t rows() const;
size_t cols() const;
};
int main()
{
Matrix2D<int> foo(10, 10, 0);
foo(8, 3) = 42;
foo(9, 9) = 523;
cout << foo << endl;
return 0;
}
template <typename T>
Matrix2D<T>::Matrix2D()
: m_rows(0), m_cols(0), m_data(new T[0])
{
}
template <typename T>
Matrix2D<T>::Matrix2D(size_t rows, size_t cols)
: m_rows(rows), m_cols(cols), m_data(new T[rows * cols])
{
}
template <typename T>
Matrix2D<T>::Matrix2D(size_t rows, size_t cols, T initial_value)
: m_rows(rows), m_cols(cols), m_data(new T[rows * cols])
{
for (T *start = m_data; start != m_data + m_rows * m_rows; start++)
{
*start = initial_value;
}
}
template <typename T>
Matrix2D<T>::Matrix2D(const Matrix2D<T>& m)
: m_rows(m.m_rows), m_cols(m.m_cols),
m_data(new T[m.m_rows * m.m_cols])
{
for (size_t i = 0; i < m.m_rows * m.m_cols; i++)
{
m_data[i] = m.m_data[i];
}
}
template <typename T>
Matrix2D<T>& Matrix2D<T>::operator=(const Matrix2D<T>& m)
{
delete [] m_data;
m_rows = m.m_rows;
m_cols = m.m_cols;
m_data = new T[m_rows * m_cols];
for (size_t i = 0; i < m_rows * m_cols; i++)
{
m_data[i] = m.m_data[i];
}
return *this;
}
template <typename T>
T &Matrix2D<T>::operator()(size_t row, size_t col)
{
return m_data[row * m_cols + col];
}
template <typename T>
T Matrix2D<T>::operator()(size_t row, size_t col) const
{
return m_data[row * m_cols + col];
}
template <typename T>
ostream& operator<<(ostream& out, const Matrix2D<T>& m)
{
size_t max_len = m.max_string_length();
for (int r = 0; r < m.m_rows; r++)
{
for (int c = 0; c < m.m_cols; c++)
{
stringstream ss;
ss << m(r, c);
size_t cur_len = ss.str().length();
for (int i = 0; i < max_len - cur_len; i++)
{
out << " ";
}
out << m(r, c);
if (c == m.m_cols - 1)
{
if (r != m.m_rows - 1)
{
out << endl;
}
}
else
{
out << " | ";
}
}
}
return out;
}
template <typename T>
size_t Matrix2D<T>::max_string_length() const
{
size_t len = 0;
for (int r = 0; r < m_rows; r++)
{
for (int c = 0; c < m_cols; c++)
{
stringstream ss;
ss << (*this)(r, c);
size_t cur_len = ss.str().length();
if (cur_len > len)
{
len = cur_len;
}
}
}
return len;
}
template <typename T>
size_t Matrix2D<T>::rows() const
{
return m_rows;
}
template <typename T>
size_t Matrix2D<T>::cols() const
{
return m_cols;
}
|