按行的总和对矩阵进行排序

Sort a matrix by the sum of the rows

本文关键字:排序      更新时间:2023-10-16

我必须按行的总和对矩阵进行排序,小总和必须是第一个,更大的,最后必须是最大的总和。 我已经这样做了,但我无法完成它:

#include <iostream>
using namespace std;
int main ()
{
int **matrix;
int i, j, count, row, col, sum, temp;
cout << "n Enter the number of rows and columns";
cin >> row >> col;
matrix = new int *[row];
for (count = 0; count < row; count++)
matrix[count] = new int[col];
cout << "nNow enter the element for the matrix.";
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
cout << "nRow " << (i + 1) << " Col " << (j + 1) << " :";
cin >> *(*(matrix + i) + j);
}
}
for (i = 0; i < row; i++)
{
sum = 0;
for (j = 0; j < col; j++)
sum = sum + matrix[i][j];
cout << sum << endl;
}
for (int count = 0; count < row; count++)
delete[]matrix[count];
delete[]matrix;
matrix = 0;
return 0;
}

您可以使用标准算法std::sortstd::accumulate。下面是一个演示程序,展示了如何结合使用这些算法。

#include <iostream>
#include <algorithm>
#include <numeric>
#include <cstdlib>
#include <ctime>
int main() 
{
const size_t M = 3, N = 5;
std::srand( ( unsigned int )std::time( nullptr ) );
int **matrix = new int *[M];
for ( size_t i = 0; i < M; i++ ) matrix[i] = new int[N];
for ( size_t i = 0; i < M; i++ )
{
for ( size_t j = 0; j < N; j++ ) matrix[i][j] = std::rand() % ( M * N );
}

for ( size_t i = 0; i < M; i++ )
{
for ( size_t j = 0; j < N; j++ ) std::cout << matrix[i][j]  << ' ';
std::cout << 'n';
}
std::cout << 'n';
auto sort_by_sum = [N]( const auto &left, const auto &right )
{
return std::accumulate( left, left + N, 0ll ) < 
std::accumulate( right, right + N, 0ll );
};
std::sort( matrix, matrix + M, sort_by_sum );
for ( size_t i = 0; i < M; i++ )
{
for ( size_t j = 0; j < N; j++ ) std::cout << matrix[i][j]  << ' ';
std::cout << 'n';
}
std::cout << 'n';
return 0;
}

程序输出可能如下所示

11 2 4 14 0 
9 7 9 4 14 
10 7 5 0 7 
10 7 5 0 7 
11 2 4 14 0 
9 7 9 4 14