Реализация матрицы на с++
#include <iostream>
using namespace std;
class Matrix {
private:
int** matrix;
int rows{};
int cols{};
void swapCols(int c1, int c2) {
for (int i = 0; i < rows; i++) {
int temp = matrix[i][c1];
matrix[i][c1] = matrix[i][c2];
matrix[i][c2] = temp;
}
}
public:
int compareTo(Matrix other) {
int sum1{};
int sum2{};
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
sum1 += matrix[i][j];
}
}
for (int i = 0; i < other.rows; i++) {
for (int j = 0; j < other.cols; j++) {
sum2 += other.matrix[i][j];
}
}
return sum1 - sum2;
}
bool operator >(Matrix other) {
return compareTo(other) > 0;
}
bool operator <(Matrix other) {
return compareTo(other) < 0;
}
bool operator ==(Matrix other) {
return compareTo(other) == 0;
}
bool operator >=(Matrix other) {
return compareTo(other) >= 0;
}
bool operator <=(Matrix other) {
return compareTo(other) <= 0;
}
bool operator !=(Matrix other) {
return compareTo(other) != 0;
}
void operator =(Matrix& other) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j]=other.matrix[i][j];
}
}
}
int* operator[](int index) {
return this->matrix[index];
}
void sortCols() {
for (int i = 1; i < rows; i++) {
for (int j = i; j < rows; j++) {
if (matrix[0][j - 1] > matrix[0][j]) {
swapCols(j - 1, j);
}
}
}
}
void sortRows() {
for (int i = 1; i < rows; i++) {
for (int j = i; j < rows; j++) {
if (matrix[j - 1][0] > matrix[j][0]) {
int* tempRow = matrix[j - 1];
matrix[j - 1] = matrix[j];
matrix[j] = tempRow;
}
}
}
}
void transposition() {
int** tempMatrix = new int* [cols];
for (int i = 0; i < rows; i++) {
tempMatrix[i] = new int[cols];
for (int j = 0; j < cols; j++) {
tempMatrix[i][j] = matrix[i][j];
}
}
for (int i = 0; i < rows; i++) {
delete[] this->matrix[i];
}
delete[] this->matrix;
this->matrix = tempMatrix;
}
friend void
print(Matrix&);
explicit Matrix(int** matrix, int rows, int cols) {
this->matrix = new int* [rows];
for (int i = 0; i < rows; i++) {
this->matrix[i] = new int[cols];
for (int j = 0; j < cols; j++) {
this->matrix[i][j] = matrix[i][j];
}
}
this->rows = rows;
this->cols = cols;
}
~Matrix()
{
for (int i = 0; i < rows; i++) {
delete[] this->matrix[i];
}
delete[] this->matrix;
}
Matrix(const Matrix& other)
{
for (int i = 0; i < other.rows; i++)
{
for (int j = 0; j < other.cols; j++)
{
this->matrix[i][j] = other.matrix[i][j];
}
}
}
};
void print(Matrix& a) {
for (int i = 0; i < a.rows; i++) {
for (int j = 0; j < a.cols; j++) {
cout << a.matrix[i][j] << ' ';
}
cout << endl;
}
}
int main() {
srand(time(0));
int** m = new int* [3];
for (int i = 0; i < 3; i++) {
m[i] = new int[3]{ rand() % 10, rand() % 10, rand() % 10 };
}
int** m2 = new int* [3];
for (int i = 0; i < 3; i++) {
m2[i] = new int[3]{ rand() % 10, rand() % 10, rand() % 10 };
}
Matrix matrix(m, 3, 3);
Matrix matrix2(m2, 3, 3);
print(matrix);
cout << endl;
print(matrix2);
matrix.sortRows();
cout << endl;
print(matrix);
cout << endl;
matrix.sortCols();
print(matrix);
cout << endl;
matrix.transposition();
print(matrix);
cout << endl;
cout <<((matrix >= matrix2) ? "True" : "False");
cout << matrix[0][2];
delete[] m;
delete[] m2;
return 0;
}
Из-за деструктора в строке cout <<((matrix >= matrix2) ? "True" : "False"); вылазит ошибка Вызвано исключение по адресу 0x7BEEE44B (ucrtbased.dll) в ConsoleApplication3.exe: 0xC0000005: нарушение прав доступа при чтении по адресу 0xDDDDDDCD. Без деструктора все работает нормально. Не могу найти у ошибку.
Ответы (1 шт):
Первая ошибка памяти было такая, что вы неправильно написали конструктор копирования.
Matrix(const Matrix& other)
{
for (int i = 0; i < other.rows; i++)
{
for (int j = 0; j < other.cols; j++)
{
this->matrix[i][j] = other.matrix[i][j];
}
}
}
В ней память для матрицы вы вообще не выделяете, а копируете значения другой матрицы в случайные области памяти.
Заменяем её, используя уже написанный вами конструктор копирования с аргументами.
Matrix ( Matrix const & m ) : Matrix(m.matrix,m.rows,m.cols) { }
Теперь о причине вызова конструктора копирования.
Вторая ошибка, что вы при сравнивании матриц вызываете копирование аргумента :
bool operator >=(Matrix other) {
return compareTo(other) >= 0;
}
Аргумент Matrix other создаётся копированием во временный объект. То-есть вызывается конструктор копирования и после завершении функции этот объект уничтожается (вызывается деструктор).
Сложные объекты желательно передавать ссылками, чтобы не было лишнего копирования.
int compareTo(Matrix const & other) {
..
bool operator >=(Matrix const & other) {
..