写一段C++代码使用 Vector 类和定义派生类 Matrix实现矩阵的基本算术运算
时间: 2024-03-16 08:47:19 浏览: 94
c++关于矩阵的运算
4星 · 用户满意度95%
下面是使用Vector类和定义派生类Matrix实现矩阵的基本算术运算的C++代码:
```c++
#include <iostream>
#include <vector>
using namespace std;
class Vector {
public:
int size;
vector<double> data;
Vector(int n) {
size = n;
data.resize(n);
}
Vector operator+(const Vector& A) {
Vector res(size);
for (int i = 0; i < size; i++)
res.data[i] = data[i] + A.data[i];
return res;
}
Vector operator-(const Vector& A) {
Vector res(size);
for (int i = 0; i < size; i++)
res.data[i] = data[i] - A.data[i];
return res;
}
Vector operator*(const double& a) {
Vector res(size);
for (int i = 0; i < size; i++)
res.data[i] = data[i] * a;
return res;
}
double operator*(const Vector& A) {
double res = 0;
for (int i = 0; i < size; i++)
res += data[i] * A.data[i];
return res;
}
};
class Matrix : public Vector {
public:
int rows, cols;
Matrix(int m, int n) : Vector(m * n) {
rows = m;
cols = n;
}
Vector operator[](int i) {
Vector res(cols);
for (int j = 0; j < cols; j++)
res.data[j] = data[i * cols + j];
return res;
}
Matrix operator+(const Matrix& A) {
Matrix res(rows, cols);
for (int i = 0; i < size; i++)
res.data[i] = data[i] + A.data[i];
return res;
}
Matrix operator-(const Matrix& A) {
Matrix res(rows, cols);
for (int i = 0; i < size; i++)
res.data[i] = data[i] - A.data[i];
return res;
}
Matrix operator*(const double& a) {
Matrix res(rows, cols);
for (int i = 0; i < size; i++)
res.data[i] = data[i] * a;
return res;
}
Matrix operator*(const Matrix& A) {
Matrix res(rows, A.cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < A.cols; j++) {
Vector row = (*this)[i];
Vector col = A.getColumn(j);
res[i * res.cols + j] = row * col;
}
}
return res;
}
Vector getColumn(int j) {
Vector res(rows);
for (int i = 0; i < rows; i++)
res.data[i] = data[i * cols + j];
return res;
}
};
int main() {
Matrix A(3, 2);
A.data = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0};
Matrix B(2, 3);
B.data = {7.0, 8.0, 9.0, 10.0, 11.0, 12.0};
Matrix C = A * B;
for (int i = 0; i < C.rows; i++) {
for (int j = 0; j < C.cols; j++) {
cout << C[i][j] << " ";
}
cout << endl;
}
return 0;
}
```
这段代码中,Vector类表示一维向量,包含加、减、数乘和点乘等基本运算符重载;Matrix类是Vector类的派生类,表示二维矩阵,重载了加、减、数乘、矩阵乘等运算符,并且可以通过下标索引获取矩阵的行向量和列向量。在main函数中,我们定义了两个矩阵A和B,并计算它们的乘积C,最后输出结果。
阅读全文