确认是C++吗? 如果是,可以利用valarray和slice,结合STL的vector和sort,很方便实现。 下面的例子是按传统的C风格的动态二维数组写的接口,但内部的实现是C++的STL。如果你能用vector之类的容器存二维数组,实现应该更容易。
#include <iostream>
#include <iomanip>
#include <valarray>
#include <algorithm>
#include <vector>
#include <Iterator>
#include <cstdlib>
#include <ctime>
using namespace std;
typedef valarray<int> VAI;
// comparison function class
struct VAIComp {
bool operator() (VAI a, VAI b) { return a.sum() < b.sum();}
};
// helper functions
void fill_array(int **ppa, const size_t M, const size_t N);
void show_array(int **ppa, const size_t M, const size_t N);
void matrix_sort(int **ppa, const size_t M, const size_t N);
void printVector(vector<VAI> &v);
int main(int argc, char** argv)
{
size_t ROWS = 3; // self-defined ROW of the matrix (2-D) array.
size_t COLS = 4; // self-defined COL of the matrix.
int **ppa;
/* 1. create a C-style 2-D array */
// create 2-D dynamic array
ppa = new int*[COLS];
for (int i = 0; i < COLS; i++)
ppa[i] = new int [ROWS];
// fillup the 2-D array with some random numbers
fill_array(ppa, ROWS, COLS);
// display the original 2-D array
show_array(ppa, ROWS, COLS);
/* 2. sort the matrix by the sum of each columns */
matrix_sort(ppa, ROWS, COLS);
/* 3. clear-up, free 2-D array */
for (int i = 0; i < COLS; i++)
delete[] ppa[i];
delete[] ppa;
/* 4. the end */
return 0;
}
void matrix_sort(int **ppa, const size_t M, const size_t N)
{
vector<VAI> v;
VAI matrix(M*N);
// 2-D array to 1-D valarray
for (int i = 0; i < M; i++)
for (int j = 0; j < N; j++)
matrix[i*N+j] = ppa[i][j];
// slice valarray by columns to matrix, and load to vector
for (int k = 0; k < N; k++)
{
slice sva(k, M, N);
v.push_back(matrix[sva]);
}
// debug, columns in horizontal, before sorting.
//printVector(v);
//sort vector by sum of each column of matrix
sort (v.begin(), v.end(), VAIComp());
// debug, columns in horizontal, after sorting.
//printVector(v);
// convert vector of valarray (in colum) back to 2-D array
int col = 0;
for (vector<VAI>::iterator it = v.begin(); it != v.end(); ++it)
{
for (int row = 0; row < (*it).size(); row++)
{
ppa[row][col] = (*it)[row];
}
col ++;
}
// we're done here!!!
show_array(ppa, M, N);
}
void printVector(vector<VAI> &v)
{
for (vector<VAI>::iterator it = v.begin(); it != v.end(); ++it)
{
copy(&(*it)[0], &(*it)[(*it).size()], ostream_iterator<int>(cout, " "));
cout << endl;
}
cout << endl;
}
void show_array(int **ppa, const size_t M, const size_t N)
{
for (int i = 0; i < M; i++)
{
for (int j = 0; j < N; j++)
{
cout << setw(5) << ppa[i][j] << " ";
}
cout << endl;
}
cout << endl;
}
void fill_array(int **ppa, const size_t M, const size_t N)
{
//self-definied random boundary.
const size_t _min = 1;
const size_t _max = 100;
//initialize random seeds
srand(time(NULL));
// generate random number between min and max.
for (int i = 0; i < M; i++)
for (int j = 0; j < N; j++)
ppa[i][j] = rand() % (_max-_min+1) + _min;
}
用了一个模拟的4x3矩阵,元素是随机生成的。 如果输入是:
4 33 9 52
91 89 48 1
60 33 25 38
输出则是
9 52 4 33
48 1 91 89
25 38 60 33