Mail.ruПочтаМой МирОдноклассникиВКонтактеИгрыЗнакомстваНовостиКалендарьОблакоЗаметкиВсе проекты

В файле дана двухмерная матрица, сформировать одномерный массив длинной N из чётных элементов квадратной матрицы

Артём Азаренко Знаток (315), закрыт 2 года назад
Написать нужно на C++
Лучший ответ
Николай Веселуха Высший разум (360635) 2 года назад
#include <fstream>
#include <iostream>
#include <vector>
#include <iomanip>
#include <cmath>
using namespace std;
pair<int**, size_t> load(const char* path) {
pair<int**, size_t> box;
ifstream inp(path);
if (inp.is_open()) {
int value;
vector<int> tmp;
while (inp >> value) tmp.push_back(value);
box.second = static_cast<size_t>(sqrt(tmp.size()));
box.first = new int* [box.second];
size_t pos = 0;
for (auto i = 0U; i < box.second; ++i) {
box.first[i] = new int[box.second];
for (auto j = 0U; j < box.second; ++j) {
box.first[i][j] = tmp[pos];
++pos;
}
}
}
return box;
}
int** destroy(int** matrix, const size_t n) {
if (matrix != nullptr) {
for (auto i = 0U; i < n; ++i) delete[] matrix[i];
delete[] matrix;
matrix = nullptr;
}
return matrix;
}
size_t count_pos(int** matrix, const size_t n) {
auto count = 0U;
for (auto i = 0U; i < n; ++i)
for (auto j = 0U; j < n; ++j)
if (matrix[i][j] > 0)
++count;
return count;
}
int* create(const size_t n) {
return new int[n];
}
int* destroy(int* vec, const size_t n) {
if (vec != nullptr) {
delete[] vec;
vec = nullptr;
}
return vec;
}
void fill_pos(int* vec, const size_t n, int** matrix, const size_t m) {
auto i = 0U;
for (auto j = 0U; j < m; ++j)
for (auto k = 0U; k < m; ++k)
if (matrix[j][k] > 0)
vec[i++] = matrix[j][k];
}
void show(int* vec, const size_t n, const streamsize w) {
for (auto i = 0U; i < n; ++i) cout << ' ' << setw(w) << vec[i];
puts("");
}
void show(int** matrix, const size_t n, const streamsize w) {
for (auto i = 0U; i < n; ++i) show(matrix[i], n, w);
puts("");
}
int main() {
auto [matrix, n] = load("matrix.txt");
show(matrix, n, 4U);
auto count = count_pos(matrix, n);
auto vec = create(count);
fill_pos(vec, count, matrix, n);
show(vec, count, 4U);
vec = destroy(vec, count);
matrix = destroy(matrix, n);
system("pause > nul");
}
Остальные ответы
Евгений Высочин Просветленный (37964) 2 года назад
А почему не трёхмерная матрица в файле?
Что так слабо? :)
Похожие вопросы