这是HackerRank(Introduction C++)上的问题。给我main()。我正在尝试为由vector>表示的矩阵编写一个类。我需要重载+使其添加我的矩阵对象。测试将输入四行:第一行将说明需要多少测试用例,第二行将指定维(第一个数字是行,第二个数字是列),第三行将给出第一个矩阵(前m个数字,用空格分隔) ,将进入第一行...然后接下来的m个数将进入第二行...等),第四行将给出第二个矩阵。
当我运行第一个测试用例时,出现了分段错误。当我在运算符定义中消除了int声明和for循环,并简单地让它返回matrixprime时,我显然对矩阵加法给出了错误的答案,但至少输出没有错误。
之前,为了访问矩阵的元素,我使用“matrix.a.at(i).at(j)”代替了“matrix.a [i] [j]”,并且对 vector 产生了out_of_range误差。我觉得这些问题在某种程度上与我的运算符定义中的临时矩阵对象(如果称呼它正确)有关,但不知道到底出了什么问题。任何帮助,将不胜感激!
enter code here
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
class Matrix {
public:
vector<vector<int>> a;
Matrix operator+ (const Matrix&);
};
Matrix Matrix::operator+ (const Matrix& matrixprime) {
Matrix matrix;
int n = matrix.a.size();
int m = matrix.a[0].size();
for (int i=0; i<n; i++) {
for (int j=0; j<m; j++) {
matrix.a[i][j] = matrix.a[i][j] + matrixprime.a[i][j];
};
};
return matrix;
};
int main () {
int cases,k;
cin >> cases;
for(k=0;k<cases;k++) {
Matrix x;
Matrix y;
Matrix result;
int n,m,i,j;
cin >> n >> m;
for(i=0;i<n;i++) {
vector<int> b;
int num;
for(j=0;j<m;j++) {
cin >> num;
b.push_back(num);
}
x.a.push_back(b);
}
for(i=0;i<n;i++) {
vector<int> b;
int num;
for(j=0;j<m;j++) {
cin >> num;
b.push_back(num);
}
y.a.push_back(b);
}
result = x+y;
for(i=0;i<n;i++) {
for(j=0;j<m;j++) {
cout << result.a[i][j] << " ";
}
cout << endl;
}
}
return 0;
}
最佳答案
使用时:
Matrix matrix;
编译器使用编译器创建的默认构造函数。它使用其默认构造函数(一个空 vector )初始化成员
a
。您需要先创建具有正确数量元素的 vector ,然后才能对其使用
at()
或oprator[]
。在 vector 为空的情况下,
int m = matrix.a[0].size();
是导致行为不确定的原因。
您需要遵循以下要求:
Matrix Matrix::operator+ (const Matrix& matrixprime)
{
// Initialize the matrix to be returned to be the same
// as the LHS of the operator.
Matrix matrix;
matrix.a = this->a;
// Now increment the elements of the matrix to be returned
// by the elements of the RHS of the operator.
int n = matrix.a.size();
for (int i=0; i<n; i++)
{
int m = matrix.a[i].size();
for (int j=0; j<m; j++)
{
matrix.a[i][j] += matrixprime.a[i][j];
}
}
return matrix;
}