Ordinare una matrice

Stiamo lavorando in C++. Ho un array bidimensionale di interi, tipo questo:

4 9 8 5 7
5 6 2 6 1
9 7 8 3 2
3 9 4 5 8
1 6 8 7 1

Voglio crearne una copia ordinata per colonne, in modo che l'output sia:

1 3 5 7 8
1 3 5 7 8
1 4 6 7 9
2 4 6 8 9
2 5 6 8 9

come fare?

La mia idea é quella di usare come appoggio un multiset. Approfittando del fatto che l'inserimento in questo container é automaticamente ordinato basta caricare i valori dall'array in input nel multiset e quindi leggerli nell'array di output.

Questo il codice risultante:

#include <iostream>
#include <set>

using namespace std;

namespace {
const int DIM = 5;

void mapper(int input[][DIM], int output[][DIM]) {
multiset<int> temp;

for (int i = 0; i < DIM; ++i) {
for (int j = 0; j < DIM; ++j) {
temp.insert(input[i][j]);
}
}

multiset<int>::const_iterator it = temp.begin();
for (int i = 0; i < DIM; ++i) {
for (int j = 0; j < DIM; ++j) {
// !!! [j][i] !!! ordered by columns
output[j][i] = *it++;
}
}
}
}

int main() {
int input[DIM][DIM] = {
4, 9, 8, 5, 7,
5, 6, 2, 6, 1,
9, 7, 8, 3, 2,
3, 9, 4, 5, 8,
1, 6, 8, 7, 1
};

for (int i = 0; i < DIM; ++i) {
for (int j = 0; j < DIM; ++j) {
cout << input[i][j] << ' ';
}
cout << endl;
}
cout << endl;

int output[DIM][DIM];
mapper(input, output);

for (int i = 0; i < DIM; ++i) {
for (int j = 0; j < DIM; ++j) {
cout << output[i][j] << ' ';
}
cout << endl;
}
cout << endl;
}

Nessun commento:

Posta un commento