I'm learning c++ now I have task to create a class Matrix, where I have to sort Matrix by their sum of elements by bulb sorting I've created some code, but it doesn't work Can you help me and check what's going wrong?
class Matrix
{
private:
int row;
int column;
int** M;
public:
Matrix(int row, int column);
Matrix(const Matrix& other);
int getRow() const {
return row;
}
int getColumn() const {
return column;
}
int sum();
void sortMatrixBySum(Matrix arr[]);
friend ostream& operator<<(ostream& os, Matrix& other);
friend istream& operator>>(istream& is, Matrix& other);
friend void operator>(Matrix& m1, Matrix& m2);
friend int operator-(Matrix& other);
~Matrix();
};
Matrix::Matrix(int row, int column) {
this->row = row;
this->column = column;
M = new int* [row];
for (int i = 0; i < row; i++) {
M[i] = new int[column];
}
cout << "--Constructor called-- " << endl;
}
Matrix::Matrix(const Matrix& other) {
this ->row = other.row;
this ->column = other.column;
M = new int* [row];
for (int i = 0; i < row; i++) {
M[i] = new int[column];
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
M[i][j] = other.M[i][j];
}
}
cout << "--Copy constructor called--" << endl;
};
int Matrix::sum() {
int sum = 0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
sum +=M[i][j];
}
}
cout << "Sum of the elements of matrix = " << sum << endl;
return sum;
}
Matrix::~Matrix() {
for (int i = 0; i < row; i++) {
delete[] M[i];
}
delete[] M;
cout << "--deconstructor called--" <<this<< endl;
}
//перегрузка <<
ostream& operator<<(ostream& os, Matrix& other)
{
os << "Overload <<:" << endl;
for (int i = 0; i < other.getRow(); i++) {
for (int j = 0; j < other.getColumn(); j++) {
os << other.M[i][j] << ' ';
}
os << endl;
}
os << endl;
return os;
}
istream& operator>>(istream& is, Matrix& other) {
cout << "Overload >>" << endl;
for (int i = 0; i < other.getRow(); i++) {
cout << "Enter the row number " << i + 1 << endl;
for (int j = 0; j < other.getColumn(); j++) {
is >> other.M[i][j];
}
cout << endl;
}
return is;
}
int main() {
int numC, numR;
cout << "Enter the number of rows: ";
cin >> numR;
cout << "Enter the number of column: ";
cin >> numC;
Matrix a(numR, numC);
Matrix b(3, 3);
cin >> a;
cin >> b;
Matrix marr[4]{
a,
b,
Matrix(3,2),
Matrix(2,2)
};
cin >> marr[2];
cin >> marr[3];
a.sortMatrixBySum(marr);
for (int i = 0; i < 4; i++) {
cout << marr[i] << endl;
}
return 0;
}
It's how i realise this sorting:
void Matrix::sortMatrixBySum(Matrix arr[]) {
for (int i = 0; i < (sizeof(arr) / sizeof(*arr)); i++) {
for (int j = i + 1; j<(sizeof(arr) / sizeof(*arr)); j++)
{
if (arr[j].sum() < arr[i].sum()) {
Matrix temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
But also I don't know how to set a size of this array, like if it's right way to check size like (sizeof(arr) / sizeof(*arr))?