OJC++【id:471】【20分】A. 【程序填空】矩阵(赋值运算符=重载)_【程序填空】矩阵(赋值运算符=重载)
题目描述
下面主函数和CVector类的部分代码,完成矩阵的赋值操作。请分析程序,补齐CVector类中需要的成员函数。
输入
测试次数t
每组测试数据格式如下:
正整数n、m,分表表示矩阵的行、列
n*m行整数数据
输出
每组测试数据输出矩阵数据,具体输出格式见样例。
IO模式
本题IO模式为标准输入/输出(Standard IO),你需要从标准输入流中读入数据,并将答案输出至标准输出流中。
输入样例1
2\\n
3 3\\n
1 2 3\\n
4 5 6\\n
7 8 9\\n
2 4\\n
10 20 30 40\\n
50 60 70 80\\n
\\n
输出样例1
Matrix:\\n
1 2 3 \\n
4 5 6 \\n
7 8 9 \\n
Matrix:\\n
10 20 30 40 \\n
50 60 70 80 \\n
\\n
#include
using namespace std;
class CVector {
int** v;
int m;
int n;
public:
CVector() { n = 0; m = 0; v = NULL; }
CVector(int** a, int b, int c) {
int i, j;
m = b; n = c;
v = new int*[m];
for (i = 0; i < m; i++) v[i] = new int[n];
for (i = 0; i<m; i++)
for (j = 0; j < n; j++)
v[i][j] = a[i][j];
}
/********** Write your code here! **********/
/*******************************************/
void display() {
cout << \"Matrix:\" << endl;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++)
cout << v[i][j] << \" \";
cout << endl;
}
}
~CVector() {
if (v != NULL) {
for (int i = 0; i < m; i++) delete[] v[i];
delete[]v;
}
}
};
int main() {
int t,m, n;
cin >> t;
while (t--) {
cin >> m >> n;
int** a;
a = new int*[m];
for (int i = 0; i < m; i++)
a[i] = new int[n];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
cin >> a[i][j];
CVector obj1(a, m, n);
CVector obj2 = obj1;
CVector obj3;
obj3 = obj2;
obj3.display();
if (a != NULL) {
for (int i = 0; i < m; i++) delete[] a[i];
delete[]a;
}
}
return 0;
}
AC代码
#includeusing namespace std;class CVector {int** v;int m;int n;public:CVector() { n = 0; m = 0; v = NULL; }CVector(int** a, int b, int c) {int i, j;m = b; n = c;v = new int*[m];for (i = 0; i < m; i++) v[i] = new int[n];for (i = 0; i<m; i++)for (j = 0; j < n; j++)v[i][j] = a[i][j];} CVector(const CVector& other) { m = other.m; n = other.n; v = new int*[m]; for(int i = 0; i < m; ++i) { v[i] = new int[n]; for(int j = 0; j < n; ++j) { v[i][j] = other.v[i][j]; } } }CVector& operator=(const CVector& other) { m = other.m; n = other.n; v = new int*[m]; for(int i = 0; i < m; ++i) { v[i] = new int[n]; for(int j = 0; j < n; ++j) { v[i][j] = other.v[i][j]; }} return *this; }void display() {cout << \"Matrix:\" << endl;for (int i = 0; i < m; i++) {for (int j = 0; j < n; j++)cout << v[i][j] << \" \";cout << endl;}}~CVector() {if (v != NULL) {for (int i = 0; i > t;while (t--) {cin >> m >> n;int** a;a = new int*[m];for (int i = 0; i < m; i++)a[i] = new int[n];for (int i = 0; i < m; i++)for (int j = 0; j > a[i][j];CVector obj1(a, m, n);CVector obj2 = obj1;CVector obj3;obj3 = obj2;obj3.display();if (a != NULL) {for (int i = 0; i < m; i++) delete[] a[i];delete[]a;}}return 0;}