一个C++矩阵类的实现

#ifndef _MATRIX_H_

#define _MATRIX_H_

#include <vector>

using std::vector;


/*类功能:矩阵类

 *原理:采用数组的数组来实现

*/

template<typename T>

class SeqMatrix

{

public:

explicit SeqMatrix(size_t row=0,size_t col=0)

:arrayList(row)

{

for(size_t i=0;i<row;++i)

arrayList[i].resize(col);

}


SeqMatrix(const SeqMatrix &matrix)

:arrayList(matrix.rows())

{

for(size_t i=0;i<matrix.rows();++i)

{

arrayList[i].resize(matrix.colums());

arrayList[i]=matrix[i];

}

}


virtual ~SeqMatrix()

{

}


void resize(size_t row,size_t col)

{

arrayList.resize(row);

for(size_t i=0;i<row;++i)

arrayList[i].resize(col);

}


const size_t rows() const

{

return arrayList.size();

}


const size_t colums() const

{

if(arrayList.size()>0)

return arrayList[0].size();


return 0;

}


vector<T>& operator[](size_t row)

{

return arrayList[row];

}


const vector<T>& operator[](size_t row) const

{

return arrayList[row];

}


SeqMatrix& operator=(const SeqMatrix &rhs)

{

if(this==&rhs)

return *this;


resize(rhs.rows(),rhs.colums());

for(size_t i=0;i<rhs.rows();++i)

arrayList[i]=rhs[i];

}


private:

vector<vector<T>> arrayList;

};




#endif

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的 C++ 矩阵实现矩阵相乘的示例代码: ```c++ #include <iostream> #include <vector> using namespace std; class Matrix { private: vector<vector<int>> data; // 存储矩阵的二维向量 int m, n; // 矩阵的行数和列数 public: // 构造函数 Matrix(int rows, int cols) { m = rows; n = cols; data.resize(m, vector<int>(n, 0)); // 初始化矩阵为全零矩阵 } // 矩阵相乘运算符重载 Matrix operator*(const Matrix& other) { if (n != other.m) { cout << "矩阵维度不匹配,无法相乘" << endl; return Matrix(0, 0); } Matrix result(m, other.n); for (int i = 0; i < m; i++) { for (int j = 0; j < other.n; j++) { int temp = 0; for (int k = 0; k < n; k++) { temp += data[i][k] * other.data[k][j]; } result.data[i][j] = temp; } } return result; } // 矩阵赋值运算符重载 Matrix& operator=(const Matrix& other) { if (this == &other) { return *this; } m = other.m; n = other.n; data = other.data; return *this; } // 打印矩阵 void print() { for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { cout << data[i][j] << " "; } cout << endl; } } }; int main() { Matrix A(2, 3); Matrix B(3, 2); A.print(); B.print(); A = {{1, 2, 3}, {4, 5, 6}}; B = {{7, 8}, {9, 10}, {11, 12}}; A.print(); B.print(); Matrix C = A * B; C.print(); return 0; } ``` 这个示例代码中,我们定义了一个 `Matrix` 来表示矩阵,并实现矩阵相乘的运算符重载。在 `main()` 函数中,我们创建了两个矩阵 `A` 和 `B`,并将它们赋值为我们需要相乘的矩阵。然后,我们通过 `A * B` 的方式来计算它们的乘积,并将结果存储在 `C` 中。最后,我们打印了 `C` 的值,即矩阵相乘的结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值