使用c++实现矩阵加法和矩阵转置运算
时间: 2024-09-29 16:11:01 浏览: 45
在C++中,我们可以创建类来表示矩阵,并提供相应的成员函数来实现矩阵加法和转置操作。这里是一个简单的例子:
```cpp
#include <iostream>
#include <vector>
class Matrix {
private:
std::vector<std::vector<int>> data; // 矩阵数据
int rows, cols;
public:
Matrix(int r, int c) : rows(r), cols(c) {} // 构造函数
// 添加行数列数相同的矩阵
Matrix operator+(const Matrix& other) const {
if (rows != other.rows || cols != other.cols)
throw std::invalid_argument("Matrices must have the same dimensions for addition.");
Matrix result(rows, cols);
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
result.data[i][j] = data[i][j] + other.data[i][j];
}
}
return result;
}
// 返回转置后的矩阵
Matrix transpose() const {
Matrix transposed(cols, rows);
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
transposed.data[j][i] = data[i][j]; // 交换行和列
}
}
return transposed;
}
void display() const { // 打印矩阵
for (auto row : data) {
for (int element : row) {
std::cout << element << " ";
}
std::cout << "\n";
}
}
};
int main() {
Matrix m1(2, 2);
m1.data = {{1, 2}, {3, 4}};
Matrix m2(2, 2);
m2.data = {{5, 6}, {7, 8}};
std::cout << "Matrix 1:\n";
m1.display();
std::cout << "Matrix 2:\n";
m2.display();
Matrix sum = m1 + m2;
std::cout << "Sum of matrices:\n";
sum.display();
Matrix transposed = m1.transpose();
std::cout << "Transposed of matrix 1:\n";
transposed.display();
return 0;
}
```
这个程序定义了一个`Matrix`类,它有加法(`+`)、转置(`transpose`)以及显示(`display`)方法。在`main()`函数里,我们创建了两个矩阵并进行了加法和转置操作。
阅读全文