6-1 可变大小矩阵 分数 10 作者 杨军 单位 四川师范大学 完成一个矩阵类,可以存放二维数据,在构造函数中通过参数指定行数和列数,具有矩阵转置的功能和显示数据的功能。要求实现该矩阵类,使得主函数中的测试代码可以正确运行并得到正确的结果。 函数接口定义: 实现矩阵类 裁判测试程序样例: /* 请在这里填写答案 */ int main(){ int r,c; cin>>r>>c; Matrix m(r,c); // 初始大小 2行3列 m.input(); cout<<"datas before:"<<endl; m.show(); m.transform(); cout<<"datas after:"<<endl; m.show(); } 输入样例: 首先输入两个整数代表行数和列数,然后输入矩阵元素。 3 2 1 2 3 4 5 6 输出样例: 分别输出转置之前和之后的矩阵数据。例如: datas before: 1 2 3 4 5 6 datas after: 1 3 5 2 4 6 代码长度限制 16 KB 时间限制 400 ms
时间: 2024-03-09 10:45:25 浏览: 123
以下是可变大小矩阵的代码实现:
```cpp
#include <iostream>
using namespace std;
class Matrix {
private:
int rows; // 矩阵行数
int cols; // 矩阵列数
int **data; // 存放二维数据的指针
public:
// 构造函数,初始化矩阵大小并动态分配内存
Matrix(int r, int c) {
rows = r;
cols = c;
data = new int*[rows];
for (int i = 0; i < rows; i++) {
data[i] = new int[cols];
}
}
// 析构函数,释放内存
~Matrix() {
for (int i = 0; i < rows; i++) {
delete[] data[i];
}
delete[] data;
}
// 矩阵转置
void transform() {
int **newData = new int*[cols];
for (int i = 0; i < cols; i++) {
newData[i] = new int[rows];
for (int j = 0; j < rows; j++) {
newData[i][j] = data[j][i];
}
}
// 释放原有内存
for (int i = 0; i < rows; i++) {
delete[] data[i];
}
delete[] data;
// 更新矩阵大小和数据
int temp = rows;
rows = cols;
cols = temp;
data = newData;
}
// 显示数据
void show() {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << data[i][j] << " ";
}
cout << endl;
}
}
// 输入数据
void input() {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cin >> data[i][j];
}
}
}
};
int main() {
int r, c;
cin >> r >> c;
Matrix m(r, c); // 初始大小 r 行 c 列
m.input(); // 输入数据
cout << "datas before:" << endl;
m.show(); // 显示数据
m.transform(); // 转置矩阵
cout << "datas after:" << endl;
m.show(); // 显示转置后的数据
return 0;
}
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)