数据结构——矩阵

本文详细介绍了矩阵在数据结构中的存储方法,包括对角矩阵、三角矩阵、对称矩阵的压缩存储,以及稀疏矩阵的三元组表和十字链表存储方式。并讨论了矩阵运算的时间复杂性,如矩阵转置的时间复杂性为O(nt)。
摘要由CSDN通过智能技术生成

                                     数据结构——矩阵

 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 +
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值