C/C++
Помогите написать программу по обработке двухмерного массива в с++
Написать программу по обработке двухмерного массива , размеры массива n,m и значения его элементов вводятся с клавиатуры. В матрице размером nxm упорядочить строки по возрастанию суммы их элементов
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <numeric>
#include <limits>
using namespace std;
size_t length(const char* msg) {
auto value = 0U;
while (!value) {
cout << msg;
cin >> value;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
return value;
}
int* create(const size_t n) {
if (0U == n) return nullptr;
auto row = new(nothrow) int[n];
if (row != nullptr) memset(row, 0, n * sizeof(int));
return row;
}
int* destroy(int* row) {
if (row != nullptr) {
delete[] row;
row = nullptr;
}
return row;
}
int** create(const size_t n, const size_t m) {
if (0U == n || 0U == m) return nullptr;
auto matrix = new(nothrow) int* [n];
if (matrix != nullptr) {
for (auto i = 0U; i < n; ++i) {
matrix[i] = create(m);
if (matrix[i] == nullptr) {
for (auto j = 0U; j < i; ++j) delete[] matrix[j];
delete[] matrix;
matrix = nullptr;
break;
}
}
}
return matrix;
}
int** destroy(int** matrix, const size_t n) {
if (matrix != nullptr) {
for (auto i = 0U; i < n; ++i) matrix[i] = destroy(matrix[i]);
delete[] matrix;
matrix = nullptr;
}
return matrix;
}
void input(int* p, const size_t n) {
if (p && n) for (auto i = 0U; i < n; ++i) cin >> p[i];
}
void input(int** mx, const size_t n, const size_t m) {
if (mx && n) for (auto i = 0U; i < n; ++i) input(mx[i], m);
}
void show(int* p, const size_t n, const streamsize w = 3) {
if (p && n) for (auto i = 0U; i < n; ++i) cout << ' ' << setw(w) << p[i];
puts("");
}
void show(int** mx, const size_t n, const size_t m, const streamsize w = 3) {
if (mx && n) for (auto i = 0U; i < n; ++i) show(mx[i], m, w);
puts("");
}
long long sum(int* p, const size_t n) {
if (p && n) return accumulate(p, p + n, 0LL);
return 0LL;
}
int main() {
auto n = length("n: ");
auto m = length("m: ");
auto matrix = create(n, m);
if (matrix != nullptr) {
puts("Input matrix:");
input(matrix, n, m);
system("cls");
show(matrix, n, m);
auto compare = [m](int* a, int* b) {
return sum(a, m) < sum(b, m);
};
sort(matrix, matrix + n, compare);
show(matrix, n, m);
destroy(matrix, n);
system("pause > nul");
}
}
#include <iostream>
#include <iomanip>
#include <numeric>
#include <limits>
using namespace std;
size_t length(const char* msg) {
auto value = 0U;
while (!value) {
cout << msg;
cin >> value;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
return value;
}
int* create(const size_t n) {
if (0U == n) return nullptr;
auto row = new(nothrow) int[n];
if (row != nullptr) memset(row, 0, n * sizeof(int));
return row;
}
int* destroy(int* row) {
if (row != nullptr) {
delete[] row;
row = nullptr;
}
return row;
}
int** create(const size_t n, const size_t m) {
if (0U == n || 0U == m) return nullptr;
auto matrix = new(nothrow) int* [n];
if (matrix != nullptr) {
for (auto i = 0U; i < n; ++i) {
matrix[i] = create(m);
if (matrix[i] == nullptr) {
for (auto j = 0U; j < i; ++j) delete[] matrix[j];
delete[] matrix;
matrix = nullptr;
break;
}
}
}
return matrix;
}
int** destroy(int** matrix, const size_t n) {
if (matrix != nullptr) {
for (auto i = 0U; i < n; ++i) matrix[i] = destroy(matrix[i]);
delete[] matrix;
matrix = nullptr;
}
return matrix;
}
void input(int* p, const size_t n) {
if (p && n) for (auto i = 0U; i < n; ++i) cin >> p[i];
}
void input(int** mx, const size_t n, const size_t m) {
if (mx && n) for (auto i = 0U; i < n; ++i) input(mx[i], m);
}
void show(int* p, const size_t n, const streamsize w = 3) {
if (p && n) for (auto i = 0U; i < n; ++i) cout << ' ' << setw(w) << p[i];
puts("");
}
void show(int** mx, const size_t n, const size_t m, const streamsize w = 3) {
if (mx && n) for (auto i = 0U; i < n; ++i) show(mx[i], m, w);
puts("");
}
long long sum(int* p, const size_t n) {
if (p && n) return accumulate(p, p + n, 0LL);
return 0LL;
}
int main() {
auto n = length("n: ");
auto m = length("m: ");
auto matrix = create(n, m);
if (matrix != nullptr) {
puts("Input matrix:");
input(matrix, n, m);
system("cls");
show(matrix, n, m);
auto compare = [m](int* a, int* b) {
return sum(a, m) < sum(b, m);
};
sort(matrix, matrix + n, compare);
show(matrix, n, m);
destroy(matrix, n);
system("pause > nul");
}
}
Pro100Rahat Pro100Rahat
идентификатор "sort" не определен
Я долго думал вчера над этой программой. Но у меня она не получилась.
Покажу, какой сейчас есть код. Вроде бы по логике он должен работать правильно, но почему-то не работает. Может быть ты поймёшь, в чём ошибка.
#include <iostream>
#include <ctime>
using namespace std;
// находим индекс в массиве сумм строк
// сумма строки которого минимальна
int i_min_sum(const int * sum, const int n)
{
int i_min = 0;
for(int x = 1; x < n; x++)
if(sum[x] < sum[i_min]) i_min = x;
return i_min;
}
// находим индекс в массиве строк
// сумма строки которого следующая по минимальности
// то есть немного больше
int i_next_min_sum(const int * sum, const int n, const int min)
{
int next = 0;
for(int x = 1; x < n; x++)
{
if(sum[x] < sum[next])
if(sum[x] > sum[min])
next = x;
}
return next;
}
int main()
{
int n,m;
cin >> n;
cin >> m;
int ** arr;
arr = new int *[n];
for(int x = 0; x < n; x++)
arr[x] = new int[m];
int * sum;
sum = new int[n];
int ** copy;
copy = new int* [n];
for(int x = 0; x < n; x++)
copy[x] = new int[m];
srand(time(NULL));
for(int x = 0; x < n; x++)
{
for(int y = 0; y < m; y++)
{
arr[x][y] = rand() % 11;
cout << arr[x][y] << '\t';
}
cout << endl;
}
// считаем суммы строчек
for(int x = 0; x < n; x++)
{
sum[x] = 0;
for(int y = 0; y < m; y++)
{
sum[x] += arr[x][y];
}
}
// находим строку с наименьшей суммой
int min = i_min_sum(sum, n);
//cout << "min = " << min << endl;
int count_find = 0;
// копируем строки в сортированном виде
while(count_find < n)
{
for(int x = 0; x < n; x++)
{
if(sum[x] == sum[min])
{
for(int y = 0; y < m; y++)
{
copy[count_find][y] = arr[x][y];
}
count_find++;
}
}
min = i_next_min_sum(sum, n, min);
}
// обратное копирование
for(int x = 0; x < n; x++)
for(int y = 0; y < m; y++)
arr[x][y] = copy[x][y];
// теперь надо вывести массив на экран
cout << endl;
for(int x = 0; x < n; x++)
{
for(int y = 0; y < m; y++)
{
cout << arr[x][y] << '\t';
}
cout << endl;
}
for(int x = 0; x < n; x++)
delete [] copy [x];
delete [] copy;
copy = NULL;
delete [] sum;
sum = NULL;
for(int x = 0; x < n; x++)
delete [] arr[x];
delete [] arr;
arr = NULL;
return 0;
}
Покажу, какой сейчас есть код. Вроде бы по логике он должен работать правильно, но почему-то не работает. Может быть ты поймёшь, в чём ошибка.
#include <iostream>
#include <ctime>
using namespace std;
// находим индекс в массиве сумм строк
// сумма строки которого минимальна
int i_min_sum(const int * sum, const int n)
{
int i_min = 0;
for(int x = 1; x < n; x++)
if(sum[x] < sum[i_min]) i_min = x;
return i_min;
}
// находим индекс в массиве строк
// сумма строки которого следующая по минимальности
// то есть немного больше
int i_next_min_sum(const int * sum, const int n, const int min)
{
int next = 0;
for(int x = 1; x < n; x++)
{
if(sum[x] < sum[next])
if(sum[x] > sum[min])
next = x;
}
return next;
}
int main()
{
int n,m;
cin >> n;
cin >> m;
int ** arr;
arr = new int *[n];
for(int x = 0; x < n; x++)
arr[x] = new int[m];
int * sum;
sum = new int[n];
int ** copy;
copy = new int* [n];
for(int x = 0; x < n; x++)
copy[x] = new int[m];
srand(time(NULL));
for(int x = 0; x < n; x++)
{
for(int y = 0; y < m; y++)
{
arr[x][y] = rand() % 11;
cout << arr[x][y] << '\t';
}
cout << endl;
}
// считаем суммы строчек
for(int x = 0; x < n; x++)
{
sum[x] = 0;
for(int y = 0; y < m; y++)
{
sum[x] += arr[x][y];
}
}
// находим строку с наименьшей суммой
int min = i_min_sum(sum, n);
//cout << "min = " << min << endl;
int count_find = 0;
// копируем строки в сортированном виде
while(count_find < n)
{
for(int x = 0; x < n; x++)
{
if(sum[x] == sum[min])
{
for(int y = 0; y < m; y++)
{
copy[count_find][y] = arr[x][y];
}
count_find++;
}
}
min = i_next_min_sum(sum, n, min);
}
// обратное копирование
for(int x = 0; x < n; x++)
for(int y = 0; y < m; y++)
arr[x][y] = copy[x][y];
// теперь надо вывести массив на экран
cout << endl;
for(int x = 0; x < n; x++)
{
for(int y = 0; y < m; y++)
{
cout << arr[x][y] << '\t';
}
cout << endl;
}
for(int x = 0; x < n; x++)
delete [] copy [x];
delete [] copy;
copy = NULL;
delete [] sum;
sum = NULL;
for(int x = 0; x < n; x++)
delete [] arr[x];
delete [] arr;
arr = NULL;
return 0;
}
Валерий Маймескул
Только у меня не ручной ввод, а автоматический. Чтобы вручную вводит, нужно убрать
#include <ctime>
srand(time(NULL));
rand()
и сделать
cin >> arr[x][y];
#include <ctime>
srand(time(NULL));
rand()
и сделать
cin >> arr[x][y];
#include <iostream>
using namespace std;
int main()
{
int n, m;
cin >> n >> m;
int** A = new int* [n];
for (int i = 0; i < n; i++)
A[i] = new int[m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cin >> A[i][j];
int** S = new int* [n];
for (int i = 0; i < n; i++)
S[i] = new int[2];
for (int i = 0; i < n; i++)
{
S[i][0] = i; S[i][1] = 0;
for (int j = 0; j < m; j++)
S[i][1] += A[i][j];
}
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
if (S[i][1] > S[j][1])
{
int tmp = S[i][0];
S[i][0] = S[j][0];
S[j][0] = tmp;
tmp = S[i][1];
S[i][1] = S[j][1];
S[j][1] = tmp;
}
/*for (int i = 0; i < n; i++)
{
for (int j = 0; j < 2; j++)
{
cout.width(3);
cout << S[i][j];
}
cout << endl;
} cout << endl;*/
int** B = new int* [n];
for (int i = 0; i < n; i++)
B[i] = new int[m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
B[i][j] = A[S[i][0]][j];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cout.width(3);
cout << B[i][j];
}
cout << endl;
} cout << endl;
for (int i = 0; i < n; i++)
delete[] A[i];
for (int i = 0; i < n; i++)
delete[] S[i];
for (int i = 0; i < n; i++)
delete[] B[i];
return 0;
}
using namespace std;
int main()
{
int n, m;
cin >> n >> m;
int** A = new int* [n];
for (int i = 0; i < n; i++)
A[i] = new int[m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cin >> A[i][j];
int** S = new int* [n];
for (int i = 0; i < n; i++)
S[i] = new int[2];
for (int i = 0; i < n; i++)
{
S[i][0] = i; S[i][1] = 0;
for (int j = 0; j < m; j++)
S[i][1] += A[i][j];
}
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
if (S[i][1] > S[j][1])
{
int tmp = S[i][0];
S[i][0] = S[j][0];
S[j][0] = tmp;
tmp = S[i][1];
S[i][1] = S[j][1];
S[j][1] = tmp;
}
/*for (int i = 0; i < n; i++)
{
for (int j = 0; j < 2; j++)
{
cout.width(3);
cout << S[i][j];
}
cout << endl;
} cout << endl;*/
int** B = new int* [n];
for (int i = 0; i < n; i++)
B[i] = new int[m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
B[i][j] = A[S[i][0]][j];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cout.width(3);
cout << B[i][j];
}
cout << endl;
} cout << endl;
for (int i = 0; i < n; i++)
delete[] A[i];
for (int i = 0; i < n; i++)
delete[] S[i];
for (int i = 0; i < n; i++)
delete[] B[i];
return 0;
}
Похожие вопросы
- С++.Помогите пожалуйста! Написать программу по обработке динамических массивов. Размеры массивов вводить с клавиатуры.
- Помогите с программой на с++ на массивы
- Написать программу на C++. Дан массив записей, содержащий номера телефонов сотрудников учреждения
- Помогите написать программу на С
- Помогите написать программу на C++
- Помогите написать программу на с++
- Помогите написать программу на с++
- Помогите написать программу
- Помогите написать программу на С++
- С++. Структуры(struct). Помогите написать программу