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

Объявить класс «Матрица»

10.05.2022, 02:25. Показов 448. Ответов 2
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Дана вещественная квадратная матрица А порядка n, векторы х, у с n элементами. Составить функцию, которая позволяет получить вектор c = А * (x + y)
Объявить класс «Матрица» и определить его методы.
Обеспечить представление матрицы произвольного размера с возможностью изменения числа строк и столбцов. Каждая строка матрицы – объект
класса «вектор» из задания 2.1.
Обеспечить в конструкторе автоматическое генерирование имени матрицы («матрица 1», «матрица 2» и т.д.), используя для этого статическое поле –
счетчик объектов класса.
Реализовать в классе метод вывода матрицы на экран с одновременным выводом ее имени. Алгоритм обработки, реализующий условие задачи, определить
как функцию-член класса или как дружественную функцию класса.
Обеспечить работу с безопасным массивом, т.е. контролировать выход индекса элемента массива за допустимый описанием объекта диапазон. Для этого
перегрузить оператор индексирования [ ] для обращения к элементам матрицы.
В случае выхода за пределы массива генерировать исключения с помощью ключевого слова throw.

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
#include <ctime>
#include <iostream>
#include <exception>
#include <iomanip>
#include <vector>
#include <string>
using namespace std;
 
template<typename T>
class Vector {
public:
    Vector() {}
 
    Vector(size_t size) {
        this->size = size;
        this->arr = new T[size];
    }
 
    Vector(const Vector<T>& vector) {
        this->size = vector.size;
        this->arr = new T[size];
        memcpy(this->arr, vector.arr, sizeof(T) * this->size);
    }
 
    Vector<T>& operator = (const Vector<T>& vector) {
        if (this->arr) {
            delete[] this->arr;
        }
 
        this->size = vector.size;
        this->arr = new T[size];
        memcpy(this->arr, vector.arr, sizeof(T) * this->size);
 
 
        return *this;
    }
 
    /*~Vector() {
        delete[] this->arr;
    }*/
 
    void SetSize(size_t size) {
        T* new_arr = new T[size]{};
 
        if (this->arr) {
            std::memcpy(new_arr, this->arr, sizeof(T) * std::min(size, this->size));
            delete[] this->arr;
        }
 
        this->arr = new_arr;
        this->size = size;
    }
 
    int GetSize() const {
        return this->size;
    }
 
    void Append(int element) {
        SetSize(this->size + 1);
        (*this)[this->size - 1] = element;
    }
 
    T& operator[](int index) {
        if (index < 0 || index >= size) {
            throw std::invalid_argument("index is out of bounds");
        }
 
        return this->arr[index];
    }
 
    T operator[](int index) const {
        if (index < 0 || index >= size) {
            throw std::invalid_argument("index is out of bounds");
        }
 
        return this->arr[index];
    }
    Vector operator+(const Vector& other) {
        Vector result(size);
        for (int i = 0; i < size; i++) {
            result[i] = (*this)[i] + other[i];
        }
 
        return result;
    }
 
private:
    size_t size = 0;
    T* arr = nullptr;
};
 
template<typename T>
ostream& operator << (std::ostream& os, const Vector<T>& vector)
{
    for (size_t i = 0; i < vector.GetSize(); i++) {
        os << vector[i] << " ";
    }
 
    return os;
}
 
template <typename T>
class Matrix
{
 
private:
    string _name;
    Vector<Vector<T>> _matrix;
    size_t _rows;
    size_t _cols;
 
public:
    static size_t counter;
 
private:
    void SetName()
    {
        _name = "Matrix_" + to_string(counter++);
    }
 
    void IndexValidation(size_t index) const
    {
        if (index >= _rows)
            throw invalid_argument("Invalid index!");
    }
 
public:
    Matrix() {SetName(); }
 
    Matrix(const size_t rows, const size_t cols)
    {
        //SetName();
 
        _matrix = Vector<Vector<T>>(rows);
        for (size_t i = 0; i < rows; i++)
            _matrix[i] = Vector<T>(cols);
 
        _rows = rows;
        _cols = cols;
    }
 
    size_t GetRows() const { return _rows; }
 
    size_t GetCols() const { return _cols; }
 
    string GetName() const { return _name; }
 
    void SetRows(const size_t rows)
    {
        _matrix.SetSize(rows);
        if (rows > _rows)
            for (size_t i = _rows; i < rows; i++)
                _matrix[i] = Vector<T>(_cols);
        _rows = rows;
    }
 
    void SetCols(const size_t& cols)
    {
        for (auto col : _matrix)
            col.SetSize(cols);
 
        _cols = cols;
    }
 
    Vector<T>& operator[](const size_t row)
    {
        IndexValidation(row);
        return _matrix[row];
    }
 
    const Vector<T> operator[](const size_t row) const
    {
        IndexValidation(row);
        return _matrix[row];
    }
 
    Matrix operator+(const Matrix& matrix) const
    {
        Matrix newMatrix(_rows, _cols);
        for (size_t i = 0; i < _rows; i++)
            for (size_t j = 0; j < _cols; j++)
                newMatrix[i][j] = (*this)[i][j] + matrix[i][j];
 
        return newMatrix;
    }
 
 
    Matrix operator* (const Vector<T>& v)
    {
        Matrix newMatrix(_rows, _cols);
        for (size_t i = 0; i < _rows; i++)
        {
            for (size_t j = 0; j < _cols; j++)
            {
                newMatrix[i][j] = 0;
                for (int k = 0; k < _cols; k++)
                    newMatrix[i][j] += v[i] * (*this)[k][j];
                //                  ^второй квадратной скобки быть не может
 
            }
        }
        return newMatrix;
    }
 
    Matrix& operator=(const Matrix& matrix)
    {
        for (size_t i = 0; i < _rows; i++)
            for (size_t j = 0; j < _cols; j++)
                (*this)[i][j] = matrix[i][j];
 
        return *this;
    }
 
    friend ostream& operator<<(ostream& os, const Matrix& matrix)
    {
        os << matrix.GetName() << endl;
        for (size_t i = 0; i < matrix.GetRows(); i++)
        {
            for (size_t j = 0; j < matrix.GetCols(); j++)
                os << matrix[i][j] << " ";
 
            os << endl;
        }
 
        return os;
    }
 
    void RandomFill()
    {
        for (size_t i = 0; i < _rows; i++)
        {
            for (size_t j = 0; j < _cols; j++)
            {
                _matrix[i][j] = rand() % 10 + rand() % 10 * 0.1;
            }
        }
    }
 
};
 
template <typename T>
size_t Matrix<T>::counter = 0;
 
Matrix<double> Task(Matrix<double> A, Vector<double> x, Vector<double> y)
{
    return A * (x + y);
}
 
int main()
{
    setlocale(LC_ALL, "Russian");
    Matrix<double> A;
    Vector<double> x;
    Vector<double> y;
    int n, n1, n2, n3;
    cout << "Введите порядок матрицы A" << endl;
    cin >> n;
    A.SetRows(n);
    A.SetCols(n);
    A.RandomFill();
    cout << "Введите x" << endl;
    cin >> n1;
    x.SetSize(n1);
    cout << "Введите y" << endl;
    cin >> n2;
    y.SetSize(n2);
    cout << (A * (x + y)) << Task(A, x, y) << endl;
}
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
10.05.2022, 02:25
Ответы с готовыми решениями:

Класс - матрица, как объявить нужную мне матрицу в конструкторе
имеется класс матрица class matrix { private: int **matr; int m; int n; void create() { // создание матрицы matr =...

Как объявить класс
Как объявить класс который расположен ниже по коду чем доступ к его методу? (все расположено в файле cpp) пишет: Ошибка C2027...

Объявить класс многоугольника
В программе нужно объявить класс многоугольника содержащий в себе количество точек, точки, Площадь, а так же реализовать конструктор .

2
 Аватар для lemegeton
4903 / 2696 / 921
Регистрация: 29.11.2010
Сообщений: 5,783
10.05.2022, 05:43
У вас в классе "Matrix" есть поле типа "Vector<Vector<T>>",
а в конструкторе вот такая шляпа:
C++
1
memcpy(this->arr, vector.arr, sizeof(T) * this->size);
Член класса "arr" становится нетривиально копируемого типа Vector.
Получается копирование байт по адресу, по которому находится нетривиальный тип Vector.
Так нельзя делать. Если хотите стандартных шаблонных функций, воспользуйтесь std::copy.
Например так:
C++
1
        std::copy(vector.arr, vector.arr + vector.size, this->arr);
Добавлено через 7 минут
C++
1
2
        for (auto col : _matrix)
            col.SetSize(cols);
Чтоб for-each loop можно было использовать, нужны итераторы на начало и конец диапазона у класса Vector, доступные через функции begin() и end().

Для хранения массивом будет достаточно указателей на первый элемент и элемент, после последнего.
C++
1
2
3
4
5
6
7
8
9
10
11
12
    T *begin() {
        return arr;
    }
    const T *begin() const {
        return arr;
    }
    T *end() {
        return arr + size;
    }
    const T *end() const {
        return arr + size;
    }
Добавлено через 30 минут
Ох. На самом деле ошибок гораздо, гораздо больше.
0
 Аватар для lemegeton
4903 / 2696 / 921
Регистрация: 29.11.2010
Сообщений: 5,783
10.05.2022, 13:27
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
#include <iostream>
#include <exception>
#include <iomanip>
#include <vector>
#include <string>
#include <chrono>
#include <random>
 
template<typename T>
class Vector {
public:
    using Iterator = T *;
    using ConstIterator = const T *;
 
    Vector() : size(0), data(new T[0]) {}
 
    explicit Vector(std::size_t size) : size(size), data(new T[size]{}) {}
 
    Vector(std::size_t size, const T &initial) : size(size), data(new T[size]) {
        std::fill(data, data + size, initial);
    }
 
    Vector(const Vector<T> &o) : size(o.size), data(new T[o.size]{}) {
        std::copy(o.data, o.data + o.size, data);
    }
 
    Vector<T> &operator=(const Vector<T> &o) {
        if (this != &o) {
            delete[] data;
            size = o.size;
            data = new T[size];
            std::copy(o.data, o.data + o.size, data);
        }
        return *this;
    }
 
    ~Vector() {
        delete[] data;
    }
 
    std::size_t getSize() const {
        return size;
    }
 
    void resize(std::size_t newSize) {
        if (size != newSize) {
            T *newData = new T[newSize]{};
            std::copy(data, data + std::min(size, newSize), newData);
            delete[] data;
            data = newData;
            size = newSize;
        }
    }
 
    T &operator[](std::size_t index) {
        if (index >= size) {
            throw std::invalid_argument("index is out of bounds");
        }
        return data[index];
    }
 
    const T &operator[](std::size_t index) const {
        if (index >= size) {
            throw std::invalid_argument("index is out of bounds");
        }
        return data[index];
    }
 
 
    void append(const T &value) {
        resize(size + 1);
        data[size - 1] = value;
    }
 
    Iterator begin() {
        return data;
    }
 
    const Iterator begin() const {
        return data;
    }
 
    Iterator end() {
        return data + size;
    }
 
    const Iterator end() const {
        return data + size;
    }
 
private:
    std::size_t size;
    T *data;
};
 
template<typename T>
Vector<T> operator+(const Vector<T> &a, const Vector<T> &b) {
    const Vector<T> &min = a.getSize() < b.getSize() ? a : b;
    const Vector<T> &max = a.getSize() < b.getSize() ? b : a;
    Vector<T> result(max);
    auto j = result.begin();
    for (const auto &i : min) {
        *j++ += i; // можно проще, но тогда не будет так прикольно выглядеть
    }
    return result;
}
 
template<typename T>
std::ostream &operator<<(std::ostream &os, const Vector<T> &vector) {
    for (const auto &i : vector) {
        os << i << " ";
    }
    return os;
}
 
template<typename T>
class Matrix {
public:
    using Iterator = typename Vector<Vector<T>>::Iterator;
    using ConstIterator = typename Vector<Vector<T>>::ConstIterator;
 
    Matrix() : height(0), width(0), data(0, Vector<T>(0)), name("Matrix_" + std::to_string(id++)) {}
 
    Matrix(std::size_t height, std::size_t width)
            : height(height), width(width), data(height, Vector<T>(width)), name("Matrix_" + std::to_string(id++)) {}
 
    Matrix(std::size_t height, std::size_t width, const T &initial)
            : height(height), width(width), data(height, Vector<T>(width, initial)),
              name("Matrix_" + std::to_string(id++)) {}
 
    std::size_t getHeight() const {
        return height;
    }
 
    std::size_t getWidth() const {
        return width;
    }
 
    void setHeight(std::size_t newHeight) {
        data.resize(newHeight);
        height = newHeight;
    }
 
    void setWidth(std::size_t newWidth) {
        if (width != newWidth) {
            for (auto &i : data) {
                i.resize(newWidth);
            }
            width = newWidth;
        }
    }
 
    const Vector<T> &operator[](std::size_t index) const {
        return data[index];
    }
 
    Vector<T> &operator[](std::size_t index) {
        return data[index];
    }
 
    Iterator begin() {
        return data.begin();
    }
 
    const Iterator begin() const {
        return data.begin();
    }
 
    Iterator end() {
        return data.end();
    }
 
    const Iterator end() const {
        return data.end();
    }
 
    const std::string &getName() const {
        return name;
    }
 
private:
    std::size_t height;
    std::size_t width;
    Vector<Vector<T>> data;
    std::string name;
    static std::size_t id;
};
 
template<typename T>
std::size_t Matrix<T>::id = 0;
 
template<typename T>
std::ostream &operator<<(std::ostream &out, const Matrix<T> &m) {
    out << m.getName() << ":" << std::endl;
    for (const auto &i : m) {
        out << i << std::endl;
    }
    return out;
}
 
template<typename T>
Matrix<T> operator*(const Matrix<T> &m, const Vector<T> &v) {
    if (m.getHeight() != v.getSize()) {
        throw std::invalid_argument("matrix height " + std::to_string(m.getHeight()) +
                                    " and vector size " + std::to_string(v.getSize()) + " should be equal");
    }
    Matrix<T> newMatrix(m.getHeight(), m.getWidth());
    for (size_t i = 0; i < m.getHeight(); i++) {
        for (size_t j = 0; j < m.getWidth(); j++) {
            newMatrix[i][j] = 0;
            for (int k = 0; k < m.getWidth(); k++) {
                newMatrix[i][j] += v[i] * m[k][j];
            }
        }
    }
    return newMatrix;
}
 
template<typename T, typename Generator>
void generate(Vector<T> &v, Generator generator) {
    for (auto &i : v) {
        i = generator();
    }
}
 
template<typename T, typename Generator>
void generate(Matrix<T> &v, Generator generator) {
    for (auto &i : v) {
        generate(i, generator);
    }
}
 
int main() {
    std::default_random_engine randomEngine(std::chrono::system_clock::now().time_since_epoch().count());
    std::uniform_int_distribution<int> distribution(0, 9);
    auto generator = [&randomEngine, &distribution]()->int { return distribution(randomEngine); };
 
    Vector<int> x;
    Vector<int> y;
    Matrix<int> A;
 
    std::size_t n = generator();
    x.resize(n);
    y.resize(n);
    A.setHeight(n);
    A.setWidth(n);
 
    generate(x, generator);
    generate(y, generator);
    generate(A, generator);
 
    std::cout << "x = " << x << std::endl;
    std::cout << "y = " << y << std::endl;
    std::cout << "x + y = " << (x + y) << std::endl;
    std::cout << A << std::endl;
 
    std::cout << "A * (x + Y):" << std::endl << A * (x + y);
    return 0;
}
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
10.05.2022, 13:27
Помогаю со студенческими работами здесь

Объявить класс студент. C++
Объявить класс студент с функцией считающий средний балл его оценок. С полями данных имя студента и фамилия.

Объявить и определить класс Погода
Объявить и определить класс – погода: Данные: порядковый номер дня в году; температура; количество осадков. Методы: ...

Не могу объявить шаблонный класс
Здравствуйте, имеется шаблонный класс динамического массива: template&lt;typename T&gt; class DynamicArray { public: ...

Объявить и определить класс угол
Объявить и определить класс – угол: Данные: -количество градусов, минут и секунд. Методы: -заполнение данных с клавиатуры; ...

Объявить класс и перегрузить функции и операции
Ребят, нужна Ваша помощь. Не знаю как сделать( 1) Создать класс dz, в котором должно быть одно поле char, 2 конструктора (без...


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

Или воспользуйтесь поиском по форуму:
3
Ответ Создать тему
Новые блоги и статьи
Access
VikBal 11.12.2025
Помогите пожалуйста !! Как объединить 2 одинаковые БД Access с разными данными.
Новый ноутбук
volvo 07.12.2025
Всем привет. По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне: Ryzen 5 7533HS 64 Gb DDR5 1Tb NVMe 16" Full HD Display Win11 Pro
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов На странице: https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/ нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином. Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов. . . .
Ломающие изменения в C#.NStar Alpha
Etyuhibosecyu 20.11.2025
Уже можно не только тестировать, но и пользоваться C#. NStar - писать оконные приложения, содержащие надписи, кнопки, текстовые поля и даже изображения, например, моя игра "Три в ряд" написана на этом. . .
Мысли в слух
kumehtar 18.11.2025
Кстати, совсем недавно имел разговор на тему медитаций с людьми. И обнаружил, что они вообще не понимают что такое медитация и зачем она нужна. Самые базовые вещи. Для них это - когда просто люди. . .
Создание Single Page Application на фреймах
krapotkin 16.11.2025
Статья исключительно для начинающих. Подходы оригинальностью не блещут. В век Веб все очень привыкли к дизайну Single-Page-Application . Быстренько разберем подход "на фреймах". Мы делаем одну. . .
Фото: Daniel Greenwood
kumehtar 13.11.2025
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru