数组实现矩阵转置的代码
时间: 2024-10-22 07:30:17 浏览: 38
在C++中,我们可以使用二维数组来表示矩阵,并创建一个新的二维数组来存储转置后的矩阵。这里是一个简单的例子,展示了如何将一个矩阵转置:
```cpp
#include <iostream>
// 定义矩阵类
class Matrix {
private:
int rows, cols;
int data[100][100]; // 假设矩阵最大为100x100
public:
Matrix(int r, int c) : rows(r), cols(c) {}
// 方法用于设置矩阵元素
void set(int row, int col, int value) {
if (row >= 0 && row < rows && col >= 0 && col < cols)
data[row][col] = value;
else
std::cout << "Invalid index\n";
}
// 方法用于转置矩阵
void transpose() {
int transposedData[cols][rows];
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
transposedData[j][i] = data[i][j];
}
}
// 将转置后的数据复制回原矩阵(实际上应该创建新的矩阵)
// 这里只是为了演示,实际应用应避免覆盖原始数据
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
data[i][j] = transposedData[i][j];
}
}
}
// 打印矩阵
void print() {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
std::cout << data[i][j] << ' ';
}
std::cout << '\n';
}
}
};
int main() {
Matrix matrix(3, 3);
matrix.set(0, 0, 1); // 设置初始元素
matrix.set(1, 1, 2);
matrix.set(2, 2, 3);
std::cout << "Original Matrix:\n";
matrix.print();
matrix.transpose();
std::cout << "\nTransposed Matrix:\n";
matrix.print();
return 0;
}
```
在这个示例中,`transpose()`方法遍历原矩阵,将每个元素移动到新矩阵对应的位置上。请注意,这个例子没有真正地创建一个新的转置矩阵,而是直接在原矩阵上进行了修改。在实际应用中,可能需要创建一个新的矩阵来存储转置结果。
阅读全文
相关推荐

















