写一段C++代码使用 Vector 类和定义派生类 Matrix实现n阶矩阵的基本算术运算
时间: 2024-03-16 18:48:04 浏览: 91
好的,以下是一段使用 Vector 类和 Matrix 派生类实现基本矩阵算术运算的 C++ 代码:
```c++
#include <iostream>
#include <vector>
using namespace std;
class Matrix : public vector<vector<int>> {
public:
Matrix(int n) : vector<vector<int>>(n, vector<int>(n)) {}
Matrix operator+(const Matrix& other) const {
Matrix result(size());
for (int i = 0; i < size(); i++) {
for (int j = 0; j < size(); j++) {
result[i][j] = (*this)[i][j] + other[i][j];
}
}
return result;
}
Matrix operator-(const Matrix& other) const {
Matrix result(size());
for (int i = 0; i < size(); i++) {
for (int j = 0; j < size(); j++) {
result[i][j] = (*this)[i][j] - other[i][j];
}
}
return result;
}
Matrix operator*(const Matrix& other) const {
Matrix result(size());
for (int i = 0; i < size(); i++) {
for (int j = 0; j < size(); j++) {
for (int k = 0; k < size(); k++) {
result[i][j] += (*this)[i][k] * other[k][j];
}
}
}
return result;
}
void print() const {
for (int i = 0; i < size(); i++) {
for (int j = 0; j < size(); j++) {
cout << (*this)[i][j] << " ";
}
cout << endl;
}
}
};
int main() {
Matrix a(3);
a[0][0] = 1;
a[0][1] = 2;
a[0][2] = 3;
a[1][0] = 4;
a[1][1] = 5;
a[1][2] = 6;
a[2][0] = 7;
a[2][1] = 8;
a[2][2] = 9;
Matrix b(3);
b[0][0] = 9;
b[0][1] = 8;
b[0][2] = 7;
b[1][0] = 6;
b[1][1] = 5;
b[1][2] = 4;
b[2][0] = 3;
b[2][1] = 2;
b[2][2] = 1;
Matrix c = a + b;
c.print();
Matrix d = a - b;
d.print();
Matrix e = a * b;
e.print();
return 0;
}
```
这段代码定义了一个 Matrix 类,继承自 vector<vector<int>>,表示一个 n 阶矩阵。类中重载了加、减、乘三个运算符,分别实现了矩阵加、减、乘三种基本算术运算。还定义了一个 print() 方法,用于输出矩阵。在 main() 函数中,我们创建了两个 3 阶矩阵 a 和 b,并对它们进行加、减、乘运算,最后输出结果。
阅读全文