数据结构——矩阵
1.1矩阵类
1.定义
template<class T>
class Matrix{
private:
int rows, cols; // 矩阵的行数和列数
T *element; // 矩阵的元素
public:
Matrix(int r = 0, int c = 0); // 构造函数
Matrix(const Matrix<T>& m); // 复制构造函数
~Matrix() {delete [] element; } // 析构函数
int Rows() const {return rows; } // 返回矩阵行数
int Columns() const {return cols; } // 返回矩阵列数
T & operator() (int i, int j) const; // 重载下标操作符
Matrix<T>& operator = (const Matrix<T>& m); // 重载赋值运算符
Matrix<T> operator +() const; // 重载一元加法运算符
Matrix<T> operator +(const Matrix<T> & m) const; // 重载二元加法运算符
Matrix<T> operator -() const; // 重载一元减法运算符
Matrix<T> operator -(const Matrix<T> & m) const; // 重载二元减法运算符
Matrix<T> operator *(const Matrix<T> & m) const; // 重载乘法运算符
Matrix<T> operator +=(const T& x); // 重载增值运算符
};
2.重载乘法运算符:(时间复杂性为O(rows*cols*m.cols) .)
template<class T>
Matrix<T> Matrix<T>:: operator * ( const Matrix<T> & m) const
{ if ( cols != m.rows )
{cout << “Size not matched” <<endl; exit(1);}
Matrix<T> w (rows, m.cols); // 创建一个临时矩阵,存放二矩阵相乘的结果
int ct = 0, cm = 0, cw = 0; // 设定初始位置
for ( int i =1 ; i <= rows; i++ ){
for ( int j = 1 ; j <= m.cols ; j++ )
{ T sum = element[ct]*m.element[cm] ;
for ( int k = 2 ; k <= cols ; k++ )
{ ct++; // 指向*this第i行的下一个元素
cm += m.cols; // 指向m第j列的下一个元素
sum +