С Новым годом! Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.56/9: Рейтинг темы: голосов - 9, средняя оценка - 4.56
0 / 0 / 1
Регистрация: 09.04.2018
Сообщений: 10

Класс Матрица

09.04.2018, 17:30. Показов 1883. Ответов 9
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Задание: создать класс - матрица, которая у private имеет указатель на данные действительного типа, количество строк и столбцов. Определить конструктор, деструктор, функции для изменения и вывода элементов матрицы, поиск мин и макс элементов и сумы элементов матрицы.

Проблема в том, что преподавателю не нравится указатель на указатель в двумерном массиве и он просит работать с одним указателем. Т.е. double *matr. С double **matr справился, но тут я понятия не имею как работать с ним.

Буду рад примеру как ввести/вывести таким способом.
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
09.04.2018, 17:30
Ответы с готовыми решениями:

Определить базовый класс "Матрица" и класс-потомок "Треугольная матрица"
Нужно определить класс "матрица" с возможностью динамического выделения и освобождения памяти, наполнения матрицы, сохранения и чтения из...

Класс матрица
Реализовать класс матрица, который содержит следующие методы: добавить строку к матрице, удалить строку из матрицы, получить и установить...

класс матрица
Пытаюсь сделать класс матрица. Т.к. для определения массива в с++ нужны static const, а матрица может быть произвольной, было принято...

9
 Аватар для Hitoku
1755 / 1347 / 1407
Регистрация: 28.10.2016
Сообщений: 4,267
09.04.2018, 17:35
Цитата Сообщение от Balt0 Посмотреть сообщение
он просит работать с одним указателем. Т.е. double *matr
а точно матрица нужна?
0
0 / 0 / 1
Регистрация: 09.04.2018
Сообщений: 10
09.04.2018, 17:43  [ТС]
Цитата Сообщение от Hitoku Посмотреть сообщение
а точно матрица нужна?
Да.
0
 Аватар для vlisp
1062 / 983 / 153
Регистрация: 10.08.2015
Сообщений: 5,336
09.04.2018, 17:48
выкладывай кот, телепаты все в отпуске
0
 Аватар для Fulcrum_013
2083 / 1574 / 169
Регистрация: 14.12.2014
Сообщений: 13,614
09.04.2018, 17:50
Цитата Сообщение от Balt0 Посмотреть сообщение
Проблема в том, что преподавателю не нравится указатель на указатель в двумерном массиве и он просит работать с одним указателем.
По всей видимости хочет чтобы буфер одним куском выделялся а не построчно. У нас тоже ежили построчно в цикле строки выделяли сразу спрашивали - вам что 64kb памяти одним куском мало для вашей задачи?
Т.е. по всей видимости хочет увидеть организацию матрицы вот в таком духе:
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
template<typename T>
class TMatrix{
private:
   unsigned FRows=0, FCols=0;
   T** FData=nullptr;
    void Allocate(){
         FData=new T*[FRows];
         FData[0] = new T[FCols*FRows];
         for (int i=1;i<FRows;i++) FData[i]=FData[i-1]+FCols;
   }
   void Deallocate(){
          if (FData){
               delete[] FData[0];
               delete FData[];
               FData=nullptr;
          }
   }
public:
   TMatrix(unsigned aCols,unsigned aRows):FCols(aCols),FRows(aRows){Alloacate();}
   ~TMatrix(){Deallocate();}
   T* operator [](unsigned Row){return FData[Row];}
    const T* operator [](unsigned Row) const {return FData[Row];}
};
Распределение тут показаною ну а геттеры размеров,реаллокацию если изменение размеров нужно, ранж чекинг и остальной функционал уже доделаете.
1
0 / 0 / 1
Регистрация: 09.04.2018
Сообщений: 10
09.04.2018, 19:29  [ТС]
Такое точно нет. Т.к. мы еще не учили не учили шаблоны и прочее.
Вот изначальный код
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
#include <iostream>
#include <cstdlib> 
#include <ctime> 
#include <iomanip>
using namespace std;
class Matrix
{
private:
    double** matrix;
    int N;
    int M;
    int cont = 1; // in func
public:
    int x, y;
    double value;
    void message();
    Matrix(); 
    Matrix(int n, int m); 
    ~Matrix();  
    //void Enter();
    void Show();
    void SumOfElements();
    void MaxMinElement();
    void EditMatrix();
};
void Matrix::message()
{
    cout << "Сlass was created\n";
}
 
Matrix::Matrix()
{
    bool fail = false;
    do {
        cout << "Enter rows and columns!\n";
        cout << "Rows: ";     cin >> N;
        if (cin.fail()) {
            cout << "VALID INPUT. TRY AGAIN" << endl;
            fail = true;
        }
        cin.clear();
        cin.ignore();
    } while (fail);
    do {
        fail = false;
        cout << "Colums: ";    cin >> M;
        if (cin.fail()) {
            cout << "VALID INPUT. TRY AGAIN" << endl;
            fail = true;
        }
        cin.clear();
        cin.ignore();
    } while (fail);
 
    matrix = new double*[N];
    for (int i = 0; i < N; ++i) {
        matrix[i] = new double[M];
    }
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < M; ++j) {
            matrix[i][j] = 0;
        }
    }
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < M; ++j) {
            matrix[i][j] = 1.5*(rand() % 10); // double random / random_max , a potim + random int
        }
    }
    for (int i = 0; i < N; ++i)
        for (int j = 0; j < M; ++j)
        {
            if (j % M == 0)
                cout << endl;
            cout << setw(10) << matrix[i][j];
        }
    std::cout << std::endl << endl;;
}
 
 
Matrix::Matrix(int n, int m) //  конструктор с параметрами
{
    N = n; M = m;
    matrix = new double*[N];
    for (int i = 0; i < N; ++i) {
        matrix[i] = new double[M];
    }
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < M; ++j) {
            matrix[i][j] = 0;
        }
    }
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < M; ++j) {
            matrix[i][j] = 1.5*(rand() % 10); // double random / random_max , a potim + random int
        }
    }
}
Matrix::~Matrix() // деструктор
{
    for (int i = 0; i < N; ++i)
        delete[] matrix[i];
    delete[] matrix;
}
 
/*void Matrix::Enter()
{
    int i, j;
    for (i = 0; i < N; ++i)
        for (j = 0; j < M; ++j)
            matrix[i][j] = 1.5*(rand() % 10); // double random / random_max , a potim + random int
 
}
*/
void Matrix::SumOfElements()
{
    double sum = 0;
    for (int i = 0; i < N; i++) {
        {
            for (int j = 0; j < M; j++)
                sum += matrix[i][j];
        }
    }
    cout << "Sum of elements " << sum << endl;;
 
}
void Matrix::Show() 
{
    int i, j;
 
    for (i = 0; i < N; ++i)
        for (j = 0; j < M; ++j)
        {
            if (j % M == 0)
                cout << endl;
            cout << setw(10) << matrix[i][j];
        }
    std::cout << std::endl << endl;;
}
void Matrix::EditMatrix()// змінюємо матрицю переробити в функцію
{
    bool fail = false;
    cout << "You want edit matrix? 1 - YES. 2 - NO" << endl; cin >> cont;
    while (cont == 1)
    {
        do {
            fail = false;
            cout << "Enter X and  Y!\n";
            cout << "X: ";     cin >> y;
            if (cin.fail()) {
                cout << "VALID INPUT. TRY AGAIN" << endl;
                fail = true;
            }
            cin.clear();
            cin.ignore();
        } while (fail);
        do {
            fail = false;
            cout << "Y: ";    cin >> y;
            if (cin.fail()) {
                cout << "VALID INPUT. TRY AGAIN" << endl;
                fail = true;
            }
            cin.clear();
            cin.ignore();
        } while (fail);
        cout << "Value now " << matrix[x][y] << endl;;
        cout << "Enter value "; cin >> value;
        matrix[x][y] = value;
        cout << "You continue edit matrix? 1 - YES. 2 - NO" << endl;
        cin >> cont;
    }
 
}
 
void Matrix::MaxMinElement()
{
    double min, max = 0;
    min = matrix[0][0];// найперший елемент масиву мін
    max = matrix[0][0];// і макс 
 
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < M; j++)
        {
            if (matrix[i][j] < min) min = matrix[i][j];
            if (matrix[i][j] > max) max = matrix[i][j];
        }
    }
    cout << "min = " << min << endl << "max = " << max << endl;
}
int main()
{
    bool fail = false;
    int m, n, X = 0, Y = 0;
 
    srand(time(NULL));
    Matrix m1(4,3);
    m1.Show();
    m1.EditMatrix();
    m1.Show();
    m1.SumOfElements();
    m1.MaxMinElement();
    Matrix m2;
    m2.Show();
    m1.EditMatrix();
    m1.Show();
    m1.SumOfElements();
    m1.MaxMinElement();
    system("pause");
    return 0;
}
Она просила заменить double **matrix на double *matrix.
На сколько я теперь понимаю чтобы выделить память нам нужно это делать так matrix = (double *)malloc(N * M * sizeof(int));
И вместо matrix[i][j] использовать matrix[i*N + j] ?

Добавлено через 39 минут
Все заменил и немного понял как это работает.
Программа работает не всегда

Триггер на 122 строке ( cout << setw(10) << matrix[i*N + j]; ) при заданной матрице 3х3
Так же очень часто выбивает в новом окне, что "wntdll.pdb not downloaded. wntdll.pdb contains the debug information required to find the source for the module ntdll.dll "

Еще словил триггер на system("pause");

Буду рад помощи.
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
#include <iostream>
#include <cstdlib> 
#include <ctime> 
#include <iomanip>
using namespace std;
class Matrix
{
private:
    double *matrix;
    int N;
    int M;
    int cont = 1; // in func
public:
    int x, y;
    double value;
    void message();
    Matrix();
    Matrix(int n, int m);
    ~Matrix();
    //void Enter();
    void Show();
    void SumOfElements();
    void MaxMinElement();
    void EditMatrix();
};
void Matrix::message()
{
    cout << "Сlass was created\n";
}
 
Matrix::Matrix()
{
    bool fail = false;
    do {
        cout << "Enter rows and columns!\n";
        cout << "Rows: ";     cin >> N;
        if (cin.fail()) {
            cout << "VALID INPUT. TRY AGAIN" << endl;
            fail = true;
        }
        cin.clear();
        cin.ignore();
    } while (fail);
    do {
        fail = false;
        cout << "Colums: ";    cin >> M;
        if (cin.fail()) {
            cout << "VALID INPUT. TRY AGAIN" << endl;
            fail = true;
        }
        cin.clear();
        cin.ignore();
    } while (fail);
 
    matrix = (double *)malloc(N * M * sizeof(int));
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < M; ++j) {
            matrix[i*N + j] = 1.5*(rand() % 10); // double random / random_max , a potim + random int
                }
    }
    /*for (int i = 0; i < N; ++i)
        for (int j = 0; j < M; ++j)
        {
            if (j % M == 0)
                cout << endl;
            printf("%lf",matrix[i*N + j]);
        }
    std::cout << std::endl << endl;; */
}
 
 
Matrix::Matrix(int n, int m) //  конструктор с параметрами
{
    N = n; M = m;
    matrix = (double *)malloc(N * M * sizeof(int));
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < M; ++j) {
            matrix[i*N + j] = 0;
        }
    }
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < M; ++j) {
            matrix[i*N + j] = 1.5*(rand() % 10); // double random / random_max , a potim + random int
        }
    }
}
Matrix::~Matrix() // деструктор
{
    // не работает
}
 
/*void Matrix::Enter()
{
int i, j;
for (i = 0; i < N; ++i)
for (j = 0; j < M; ++j)
matrix[i][j] = 1.5*(rand() % 10); // double random / random_max , a potim + random int
 
}
*/
void Matrix::SumOfElements()
{
    double sum = 0;
    for (int i = 0; i < N; i++) {
        {
            for (int j = 0; j < M; j++)
                sum += matrix[i*N + j];
        }
    }
    cout << "Sum of elements " << sum << endl;;
 
}
void Matrix::Show()
{
    int i, j;
 
    for (i = 0; i < N; ++i)
        for (j = 0; j < M; ++j)
        {
            if (j % M == 0)
                cout << endl;
            cout << setw(10) << matrix[i*N + j];
        }
    std::cout << std::endl << endl;;
}
void Matrix::EditMatrix()// змінюємо матрицю переробити в функцію
{
    bool fail = false;
    cout << "You want edit matrix? 1 - YES. 2 - NO" << endl; cin >> cont;
    while (cont == 1)
    {
        do {
            fail = false;
            cout << "Enter X and  Y!\n";
            cout << "X: ";     cin >> y;
            if (cin.fail()) {
                cout << "VALID INPUT. TRY AGAIN" << endl;
                fail = true;
            }
            cin.clear();
            cin.ignore();
        } while (fail);
        do {
            fail = false;
            cout << "Y: ";    cin >> y;
            if (cin.fail()) {
                cout << "VALID INPUT. TRY AGAIN" << endl;
                fail = true;
            }
            cin.clear();
            cin.ignore();
        } while (fail);
        cout << "Value now " << matrix[x*N + y] << endl;;
        cout << "Enter value "; cin >> value;
        matrix[x*N+y] = value;
        cout << "You continue edit matrix? 1 - YES. 2 - NO" << endl;
        cin >> cont;
    }
 
}
 
void Matrix::MaxMinElement()
{
    double min, max = 0;
    int i = 0; int j = 0;
    min = matrix[i*N + j];// найперший елемент масиву мін
    max = matrix[i*N + j];// і макс 
 
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < M; j++)
        {
            if (matrix[i*N + j] < min) min = matrix[i*N + j];
            if (matrix[i*N + j] > max) max = matrix[i*N + j];
        }
    }
    cout << "min = " << min << endl << "max = " << max << endl;
}
int main()
{
    bool fail = false;
    int m, n, X = 0, Y = 0;
 
    srand(time(NULL));
    Matrix m1(2, 3);
    m1.Show();
    m1.EditMatrix();
    m1.Show();
    m1.SumOfElements();
    m1.MaxMinElement(); 
    Matrix m2;
    m2.Show();
    m2.EditMatrix();
    m2.Show();
    m2.SumOfElements();
    m2.MaxMinElement();
    system("pause");
    return 0;
}
0
 Аватар для Fulcrum_013
2083 / 1574 / 169
Регистрация: 14.12.2014
Сообщений: 13,614
09.04.2018, 20:27
Balt0, Да кстати, при организации матрицы одним куском считать ее сумму, находить минимум максимум и т.д. можно одним циклом по всему буферу, а не двумя вложенными по строкам.

Добавлено через 9 минут
C++
1
2
3
4
5
6
7
8
void Matrix::SumOfElements()
{
    double sum = 0;
    auto end=matrix+N*M;
    for (auto x=matrix;x!=end; x++) sum+=*x;
    cout << "Sum of elements " << sum << endl;;
 
}
1
0 / 0 / 1
Регистрация: 09.04.2018
Сообщений: 10
16.04.2018, 23:39  [ТС]
Всем спасибо. Лабораторную сдал. Кину код, мб кому-то понадобится.
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
#include <iostream>
#include <cstdlib> 
#include <ctime> 
#include <iomanip>
using namespace std;
class Matrix
{
private:
    double *matrix;
    int N;
    int M;
public:
    Matrix();
    Matrix(int n, int m);
    ~Matrix();
    //void Enter();
    void Show();
    double sum = 0;
    double SumOfElements(double *sum);
    void MaxMinElement();
    //void MaxMinElement2();
    void EditMatrix();
};
Matrix::Matrix()
{
    bool fail = false;
    do {
        cout << "Enter rows and columns!\n";
        cout << "Rows: ";     cin >> N;
        if (cin.fail()) {
            cout << "VALID INPUT. TRY AGAIN" << endl;
            fail = true;
        }
        cin.clear();
        cin.ignore();
    } while (fail);
    do {
        fail = false;
        cout << "Colums: ";    cin >> M;
        if (cin.fail()) {
            cout << "VALID INPUT. TRY AGAIN" << endl;
            fail = true;
        }
        cin.clear();
        cin.ignore();
    } while (fail);
 
    //matrix = (double *)malloc(N * M * sizeof(double));
    matrix = new double[N*M];
 
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < M; ++j) {
            matrix[i*N + j] = (double)rand() / (double)RAND_MAX + (rand()*0.1);
                //1.5*(rand() % 10);  double random / random_max , a potim + random int
                }
    }
    /*for (int i = 0; i < N; ++i)
        for (int j = 0; j < M; ++j)
        {
            if (j % M == 0)
                cout << endl;
            printf("%lf",matrix[i*N + j]);
        }
 */
}
 
Matrix::Matrix(int n, int m) //  конструктор с параметрами
{
    N = n; M = m;
    //matrix = (double *)malloc(N * M * sizeof(double));
    matrix = new double[N*M];
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < M; ++j) {
            matrix[i*N + j] = (rand() % 101 - 50) / 10.0; // double random / random_max , a potim + random int
        }
        }
}
Matrix::~Matrix() // деструктор
{
    //free(matrix);
    delete[] matrix;
    //cout << "WOW, I WORKING" << endl;
    //getchar(); getchar();
    
}
 
/*void Matrix::Enter()
{
int i, j;
for (i = 0; i < N; ++i)
for (j = 0; j < M; ++j)
matrix[i][j] = 1.5*(rand() % 10); // double random / random_max , a potim + random int
 
}
*/
 
double Matrix::SumOfElements(double *sum)
{
    double *psum = sum;
    double *end = matrix + N*M;
    for (int i = 0; i != N*M; i++) {
        *psum += matrix[i];
    }
    // cout « "Sum of elements " « sum « endl;; - повернути sum
    return *psum;
}
void Matrix::Show()
{
    int i, j;
 
    for (i = 0; i < N; ++i)
        for (j = 0; j < M; ++j)
        {
            if (j % M == 0) cout << endl;
            //printf("%.2lf ", matrix[i*N + j]);
            cout << setw(10) << matrix[i*N+j];
        }
    std::cout << std::endl << endl;;
}
void Matrix::EditMatrix()// змінюємо матрицю переробити в функцію
{
    bool fail = false;
    int x=0, y=0;
    double value;
    int cont = 1; // in func
 
    cout << "You want edit matrix? 1 - YES. 2 - NO" << endl; cin >> cont;
    
    while (cont == 1)
    {
        do {
            fail = false;
            cout << "Enter X and  Y!\n";
            cout << "X: ";     cin >> y;
            if (cin.fail()) {
                cout << "VALID INPUT. TRY AGAIN" << endl;
                fail = true;
            }
            cin.clear();
            cin.ignore();
        } while (fail);
        do {
            fail = false;
            cout << "Y: ";    cin >> y;
            if (cin.fail()) {
                cout << "VALID INPUT. TRY AGAIN" << endl;
                fail = true;
            }
            cin.clear();
            cin.ignore();
        } while (fail);
        cout << "Value now " << matrix[x*N + y] << endl;;
        cout << "Enter value "; cin >> value;
        matrix[x*N+y] = value;
        cout << "You continue edit matrix? 1 - YES. 2 - NO" << endl;
        cin >> cont;
    }
 
}
/*void Matrix::MaxMinElement2() {
    double min,max = 0;
    auto end = matrix + N*M;
    for (auto x = matrix; x != end; x++)
    {
        if (matrix[] < min) min = matrix[x];
        if (matrix > max) max = matrix[x];
    }
}
*/
void Matrix::MaxMinElement()
{
    double min, max = 0;
    int i = 0; int j = 0;
    min = matrix[i*N + j];// найперший елемент масиву мін
    max = matrix[i*N + j];// і макс 
 
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < M; j++)
        {
            if (matrix[i*N + j] < min) min = matrix[i*N + j];
            if (matrix[i*N + j] > max) max = matrix[i*N + j];
        }
    }
    cout << "min = " << min << endl << "max = " << max << endl;
}
int main()
{
    bool fail = false;
    int m, n, X = 0, Y = 0;
    double sum = 0;
    srand(time(NULL));
    Matrix m1(3, 3);
    m1.Show();
    m1.EditMatrix();
    m1.Show();
    m1.SumOfElements(&sum);
    cout << "Sum of elements " <<sum << endl;;
    m1.MaxMinElement(); 
    Matrix m2;
    m2.Show();
    m2.EditMatrix();
    m2.Show();
    m2.SumOfElements(&sum);
    cout << "Sum of elements " << sum << endl;;
    m2.MaxMinElement();
    system("pause");
    return 0;
}
Добавлено через 43 минуты
Если у кого-то есть идеи как добавить к этому всему: конструктор копирования, перегрузка потоковых операций ввода и вывода, операции = , + , – , += , –= , *= . Помогите, а то не успеваю

Добавлено через 4 часа 43 минуты
Добавил перезагрузку операций =, +, -, +=, -=, *=

Как его сделать лучше/правильней?
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
#include <iostream>
#include <cstdlib> 
#include <ctime> 
    #include <iomanip>
    using namespace std;
class Matrix
{
private:
    double *matrix;
    int N;
    int M;
public:
    Matrix();
    Matrix(int n, int m);
    ~Matrix();
    Matrix(const Matrix &obj);
    //void Enter();
    void Show();
    double sum = 0;
    double SumOfElements(double *sum);
    void MaxMinElement();
    Matrix operator + (Matrix &m2) //перегрузка оператора додавання
    {
        if (M != m2.M || N != m2.N)
        {
            for (int i = 0; i < N; ++i) {
                for (int j = 0; j < M; ++j) {
                    matrix[i*N + j] += m2.matrix[i*N + j];
                }
            }
            return *this;
        }
        cout << "The matrix have different sizes" << endl;
        return *this;
    }
    Matrix operator - (Matrix &m2) //перегрузка оператора різниці
    {
        if (M != m2.M || N != m2.N)
        {
            for (int i = 0; i < N; ++i) {
                for (int j = 0; j < M; ++j) {
                    matrix[i*N + j] -= m2.matrix[i*N + j];
                }
            }
            return *this;
        }
        else
            cout << "The matrix have different sizes" << endl;
        return *this;
    }
    Matrix operator=(Matrix &m2)//Перегрузка оператора присвоєння
    {
        delete matrix;
        N = m2.N;
        M = m2.M;
        matrix = new double[N*M];
        for (int i = 0; i < N; ++i) {
            for (int j = 0; j < M; ++j) {
                matrix[i*N + j] = m2.matrix[i*N + j];
            }
        }
        return *this;
    }
    Matrix operator*=(double num) //перегрузка оператора множення на число
    {
        for (int i = 0; i < N; ++i) {
            for (int j = 0; j < M; ++j) {
                matrix[i*N + j] *= num;
            }
        }
        return *this;
    }
    Matrix operator+=(double num) //перегрузка оператора додавання числа
    {
        for (int i = 0; i < N; ++i) {
            for (int j = 0; j < M; ++j) {
                matrix[i*N + j] += num;
            }
        }
        return *this;
    }
    Matrix operator-=(double num) //перегрузка оператора віднімання числа
    {
        for (int i = 0; i < N; ++i) {
            for (int j = 0; j < M; ++j) {
                matrix[i*N + j] -= num;
            }
        }
        return *this;
    }
    //void MaxMinElement2();
    void EditMatrix();
};
Matrix::Matrix()
{
    bool fail = false;
    do {
        cout << "Enter rows and columns!\n";
        cout << "Rows: ";     cin >> N;
        if (cin.fail()) {
            cout << "VALID INPUT. TRY AGAIN" << endl;
            fail = true;
        }
        cin.clear();
        cin.ignore();
    } while (fail);
    do {
        fail = false;
        cout << "Colums: ";    cin >> M;
        if (cin.fail()) {
            cout << "VALID INPUT. TRY AGAIN" << endl;
            fail = true;
        }
        cin.clear();
        cin.ignore();
    } while (fail);
 
    //matrix = (double *)malloc(N * M * sizeof(double));
    matrix = new double[N*M];
 
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < M; ++j) {
            matrix[i*N + j] = (double)rand() / (double)RAND_MAX + (rand()*0.1);
                //1.5*(rand() % 10);  double random / random_max , a potim + random int
                }
    }
    /*for (int i = 0; i < N; ++i)
        for (int j = 0; j < M; ++j)
        {
            if (j % M == 0)
                cout << endl;
            printf("%lf",matrix[i*N + j]);
        }
 */
}
 
Matrix::Matrix(int n, int m) //  конструктор с параметрами
{
    N = n; M = m;
    //matrix = (double *)malloc(N * M * sizeof(double));
    matrix = new double[N*M];
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < M; ++j) {
            matrix[i*N + j] = (rand() % 101 - 50) / 10.0; // double random / random_max , a potim + random int
        }
        }
}
Matrix::~Matrix() // деструктор
{
    //free(matrix);
    delete[] matrix;
    //cout << "WOW, I WORKING" << endl;
    //getchar(); getchar();
    
}
 
/*void Matrix::Enter()
{
int i, j;
for (i = 0; i < N; ++i)
for (j = 0; j < M; ++j)
matrix[i][j] = 1.5*(rand() % 10); // double random / random_max , a potim + random int
 
}
*/
Matrix::Matrix(const Matrix &obj) //копирование
{
        N = obj.N;
        M = obj.M;
        matrix = new double[N*M];
        for (int i = 0; i < N; ++i) {
            for (int j = 0; j < M; ++j) {
                matrix[i*N + j] = obj.matrix[i*N + j];
            }
        }
}
 
double Matrix::SumOfElements(double *sum)
{
    double *psum = sum;
    double *end = matrix + N*M;
    for (int i = 0; i != N*M; i++) {
        *psum += matrix[i];
    }
    // cout « "Sum of elements " « sum « endl;; - повернути sum
    return *psum;
}
void Matrix::Show()
{
    int i, j;
 
    for (i = 0; i < N; ++i)
        for (j = 0; j < M; ++j)
        {
            if (j % M == 0) cout << endl;
            //printf("%.2lf ", matrix[i*N + j]);
            cout << setw(10) << matrix[i*N+j];
        }
    std::cout << std::endl << endl;;
}
void Matrix::EditMatrix()// змінюємо матрицю переробити в функцію
{
    bool fail = false;
    int x=0, y=0;
    double value;
    int cont = 1; // in func
 
    cout << "You want edit matrix? 1 - YES. 2 - NO" << endl; cin >> cont;
    
    while (cont == 1)
    {
        do {
            fail = false;
            cout << "Enter X and  Y!\n";
            cout << "X: ";     cin >> y;
            if (cin.fail()) {
                cout << "VALID INPUT. TRY AGAIN" << endl;
                fail = true;
            }
            cin.clear();
            cin.ignore();
        } while (fail);
        do {
            fail = false;
            cout << "Y: ";    cin >> y;
            if (cin.fail()) {
                cout << "VALID INPUT. TRY AGAIN" << endl;
                fail = true;
            }
            cin.clear();
            cin.ignore();
        } while (fail);
        cout << "Value now " << matrix[x*N + y] << endl;;
        cout << "Enter value "; cin >> value;
        matrix[x*N+y] = value;
        cout << "You continue edit matrix? 1 - YES. 2 - NO" << endl;
        cin >> cont;
    }
 
}
/*void Matrix::MaxMinElement2() {
    double min,max = 0;
    auto end = matrix + N*M;
    for (auto x = matrix; x != end; x++)
    {
        if (matrix[] < min) min = matrix[x];
        if (matrix > max) max = matrix[x];
    }
}
*/
void Matrix::MaxMinElement()
{
    double min, max = 0;
    int i = 0; int j = 0;
    min = matrix[i*N + j];// найперший елемент масиву мін
    max = matrix[i*N + j];// і макс 
 
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < M; j++)
        {
            if (matrix[i*N + j] < min) min = matrix[i*N + j];
            if (matrix[i*N + j] > max) max = matrix[i*N + j];
        }
    }
    cout << "min = " << min << endl << "max = " << max << endl;
}
int main()
{
    bool fail = false;
    int m, n, X = 0, Y = 0;
    double sum = 0;
    srand(time(NULL));
    Matrix m1(3, 3);
    m1.Show();
    m1.EditMatrix();
    m1.Show();
    m1.SumOfElements(&sum);
    cout << "Sum of elements " <<sum << endl;;
    m1.MaxMinElement(); 
    Matrix m2;
    m2.Show();
    m2.EditMatrix();
    m2.Show();
    m2.SumOfElements(&sum);
    cout << "Sum of elements " << sum << endl;;
    m2.MaxMinElement();
    system("pause");
    return 0;
}
0
0 / 0 / 1
Регистрация: 09.04.2018
Сообщений: 10
21.04.2018, 19:50  [ТС]
Ап.
Перезагрузите, пожалуйста, операторы ввода/вывода.
Никак не выходит)
0
0 / 0 / 1
Регистрация: 09.04.2018
Сообщений: 10
07.05.2018, 05:08  [ТС]
Добавлено ++m и m++
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
#include <iostream>
#include <cstdlib> 
#include <ctime> 
#include <iomanip>  
using namespace std;
class Matrix
{
private:
    double *matrix;
    int N;
    int M;
public:
    Matrix();
    Matrix(int n, int m);
    ~Matrix();
    Matrix(const Matrix &obj);
    void Show();
    double sum = 0;
    double SumOfElements(double *sum);
    void MaxMinElement();
    Matrix operator +=(double num);
    Matrix operator *=(double num);
    Matrix operator + (Matrix &m2) //перегрузка оператора додавання
    {
        if (M == m2.M && N == m2.N)
        {
            for (int i = 0; i < N; ++i) {
                for (int j = 0; j < M; ++j) {
                    matrix[i*N + j] += m2.matrix[i*N + j];
                }
            }
            return *this;
        }
        cout << "The matrix have different sizes" << endl;
        return *this;
    }
    Matrix operator - (Matrix &m2) //перегрузка оператора різниці
    {
        if (M == m2.M && N == m2.N)
        {
            for (int i = 0; i < N; ++i) {
                for (int j = 0; j < M; ++j) {
                    matrix[i*N + j] -= m2.matrix[i*N + j];
                }
            }
            return *this;
        }
        else
            cout << "The matrix have different sizes" << endl;
        return *this;
    }
    Matrix operator=(Matrix &m2)//Перегрузка оператора присвоєння
    {
        delete matrix;
        N = m2.N;
        M = m2.M;
        matrix = new double[N*M];
        for (int i = 0; i < N; ++i) {
            for (int j = 0; j < M; ++j) {
                matrix[i*N + j] = m2.matrix[i*N + j];
            }
        }
        return *this;
    }
    Matrix operator ++(int) //перегрузка оператора m++
    {
        Matrix t(*this);
        for (int i = 0; i < N; ++i) {
            for (int j = 0; j < M; ++j) {
                matrix[i*N + j]++;
            }
        }
        return t;
    }
    Matrix operator ++() //перегрузка оператора ++m
    {
        for (int i = 0; i < N; ++i) {
            for (int j = 0; j < M; ++j) {
                ++matrix[i*N + j];
            }
        }
        return *this;
    }
    friend ostream& operator << (ostream &s, const Matrix &m1)
    {
        for (int i = 0; i < m1.N; ++i) {
            for (int j = 0; j < m1.M; ++j)
            {
                s << setw(10) << m1.matrix[i*m1.N + j];
            }
            s << endl;
        }
        s << endl;
        return s;
    }
    Matrix operator-=(double num) //перегрузка оператора віднімання числа
    {
        for (int i = 0; i < N; ++i) {
            for (int j = 0; j < M; ++j) {
                matrix[i*N + j] -= num;
            }
        }
        return *this;
    }
    void EditMatrix();
};
 
Matrix Matrix:: operator+=(double num) //перегрузка оператора додавання числа
{
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < M; ++j) {
            matrix[i*N + j] += num;
        }
    }
    return *this;
}
Matrix Matrix:: operator*=(double num) //перегрузка оператора множення на число
{
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < M; ++j) {
            matrix[i*N + j] *= num;
        }
    }
    return *this;
}
Matrix::Matrix()
{
    bool fail = false;
    do {
        cout << "Enter rows and columns!\n";
        cout << "Rows: ";     cin >> N;
        if (cin.fail()) {
            cout << "VALID INPUT. TRY AGAIN" << endl;
            fail = true;
        }
        cin.clear();
        cin.ignore();
    } while (fail);
    do {
        fail = false;
        cout << "Colums: ";    cin >> M;
        if (cin.fail()) {
            cout << "VALID INPUT. TRY AGAIN" << endl;
            fail = true;
        }
        cin.clear();
        cin.ignore();
    } while (fail);
    matrix = new double[N*M];
 
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < M; ++j) {
            matrix[i*N + j] = (rand() % 101 - 50) / 10.0;
            //1.5*(rand() % 10);  
        }
    }
}
 
Matrix::Matrix(int n, int m) //  конструктор с параметрами
{
    N = n; M = m;
 
    matrix = new double[N*M];
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < M; ++j) {
            matrix[i*N + j] = (rand() % 101 - 50) / 10.0; // (double)rand() / (double)RAND_MAX + (rand()*0.1);
        }
    }
}
Matrix::~Matrix() // деструктор
{
    delete[] matrix;
}
Matrix::Matrix(const Matrix &obj) //копіювання
{
    N = obj.N;
    M = obj.M;
    matrix = new double[N*M];
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < M; ++j) {
            matrix[i*N + j] = obj.matrix[i*N + j];
        }
    }
}
 
double Matrix::SumOfElements(double *sum)
{
    double *psum = sum;
    double *end = matrix + N*M;
    for (int i = 0; i != N*M; i++) {
        *psum += matrix[i];
    }
    return *psum;
}
void Matrix::Show()
{
    int i, j;
 
    for (i = 0; i < N; ++i)
        for (j = 0; j < M; ++j)
        {
            if (j % M == 0) cout << endl;
            cout << setw(10) << matrix[i*N + j];
        }
    cout << endl << endl;
}
void Matrix::EditMatrix()
{
    bool fail = false;
    int x = 0, y = 0;
    double value;
    int cont = 1;
 
    cout << "You want edit matrix? 1 - YES. 2 - NO" << endl; cin >> cont;
 
    while (cont == 1)
    {
        do {
            fail = false;
            cout << "Enter X and  Y!\n";
            cout << "X: ";     cin >> y;
            if (cin.fail()) {
                cout << "VALID INPUT. TRY AGAIN" << endl;
                fail = true;
            }
            cin.clear();
            cin.ignore();
        } while (fail);
        do {
            fail = false;
            cout << "Y: ";    cin >> y;
            if (cin.fail()) {
                cout << "VALID INPUT. TRY AGAIN" << endl;
                fail = true;
            }
            cin.clear();
            cin.ignore();
        } while (fail);
        cout << "Value now " << matrix[x*N + y] << endl;;
        cout << "Enter value "; cin >> value;
        matrix[x*N + y] = value;
        cout << "You continue edit matrix? 1 - YES. 2 - NO" << endl;
        cin >> cont;
    }
 
}
void Matrix::MaxMinElement()
{
    double min, max = 0;
    int i = 0; int j = 0;
    min = matrix[i*N + j];// найперший елемент масиву мін
    max = matrix[i*N + j];// і макс 
 
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < M; j++)
        {
            if (matrix[i*N + j] < min) min = matrix[i*N + j];
            if (matrix[i*N + j] > max) max = matrix[i*N + j];
        }
    }
    cout << "min = " << min << endl << "max = " << max << endl;
}
int main()
{
    bool fail = false;
    int m, n, X = 0, Y = 0;
    double sum = 0;
    srand(time(NULL));
    Matrix m1(3, 3);
    m1.Show();
    m1.EditMatrix();
    m1.Show();
    m1.SumOfElements(&sum);
    cout << "Sum of elements " << sum << endl;;
    m1.MaxMinElement();
    Matrix m2;
    m2.Show();
    m2.EditMatrix();
    m2.Show();
    m2.SumOfElements(&sum);
    cout << "Sum of elements " << sum << endl;;
    m2.MaxMinElement();
    cout << endl;
    cout << "Matrix 1\n" << m1 << endl;
    cout << "Matrix 2\n" << m2 << endl;
    cout << "m1++" << endl;
    (m1++).Show();
    m1.Show();
    cout << "++m1" << endl;
    (++m1).Show();
    m1.Show();
    cout << "m+=\n";
    m1 += 100;
    cout << m1;
    /*cout << "m1*=3\n";
    m1 *= 3;
    cout << m1;
    cout << "m2=m1\n";
    m2 = m1;
    cout << m2;
    cout << "m2=m2 - m1\n";
    m2 = m2 - m1;
    cout << m2;
    */
    system("pause");
    return 0;
}
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
07.05.2018, 05:08
Помогаю со студенческими работами здесь

Класс Матрица
Ребят, помогите с прогой! Определить класс матрица. В класс включить два конструктора: создание матрицы по количеству столбцов и строк и...

класс матрица
Объявите класс TMatric, создающий тип – матрицу. Элементы – данные класса: - указатель на область памяти, в которой расположена...

Класс матрица
Здравствуйте. У меня есть класс матрицы: #pragma once #ifndef classMatrix_h #define classMatrix_h #include...

Класс Матрица
Помогите мне пожалуйста разобраться с классом реализующий матрицы. Я пытаюсь инициализировать матрицу и заполнить ее элементами но не...

Класс Матрица
Помогите пожалуйста, новичок в c++. Задание следующее: 3. Описать тип-объект MATRIX (матрица произвольной размерности M*N) и его методы:...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
10
Ответ Создать тему
Новые блоги и статьи
сукцессия микоризы: основная теория в виде двух уравнений.
anaschu 11.01.2026
https:/ / rutube. ru/ video/ 7a537f578d808e67a3c6fd818a44a5c4/
WordPad для Windows 11
Jel 10.01.2026
WordPad для Windows 11 — это приложение, которое восстанавливает классический текстовый редактор WordPad в операционной системе Windows 11. После того как Microsoft исключила WordPad из. . .
Classic Notepad for Windows 11
Jel 10.01.2026
Old Classic Notepad for Windows 11 Приложение для Windows 11, позволяющее пользователям вернуть классическую версию текстового редактора «Блокнот» из Windows 10. Программа предоставляет более. . .
Почему дизайн решает?
Neotwalker 09.01.2026
В современном мире, где конкуренция за внимание потребителя достигла пика, дизайн становится мощным инструментом для успеха бренда. Это не просто красивый внешний вид продукта или сайта — это. . .
Модель микоризы: классовый агентный подход 3
anaschu 06.01.2026
aa0a7f55b50dd51c5ec569d2d10c54f6/ O1rJuneU_ls https:/ / vkvideo. ru/ video-115721503_456239114
Owen Logic: О недопустимости использования связки «аналоговый ПИД» + RegKZR
ФедосеевПавел 06.01.2026
Owen Logic: О недопустимости использования связки «аналоговый ПИД» + RegKZR ВВЕДЕНИЕ Введу сокращения: аналоговый ПИД — ПИД регулятор с управляющим выходом в виде числа в диапазоне от 0% до. . .
Модель микоризы: классовый агентный подход 2
anaschu 06.01.2026
репозиторий https:/ / github. com/ shumilovas/ fungi ветка по-частям. коммит Create переделка под биомассу. txt вход sc, но sm считается внутри мицелия. кстати, обьем тоже должен там считаться. . . .
Расчёт токов в цепи постоянного тока
igorrr37 05.01.2026
/ * Дана цепь постоянного тока с сопротивлениями и источниками (напряжения, ЭДС и тока). Найти токи и напряжения во всех элементах. Программа составляет систему уравнений по 1 и 2 законам Кирхгофа и. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru