1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|
#include <iostream>
#include <utility>
#include <algorithm>
#include <iomanip>
int main()
{
const std::size_t N = 4 ;
const double original_matrix[N][N] =
{
{ 0, 11.80, 79.34, 78.23 },
{ 11.80, 0, 65.23, 45.19 },
{ 79.34, 65.23, 0, 90.27 },
{ 78.23, 45.19, 90.27, 0 }
};
// print out the original matrix
std::cout << std::fixed << std::setprecision(2) ;
for( const auto& row : original_matrix ) // for each row in original_matrix
{
for( double value : row ) // for each value in the row
std::cout << std::setw(7) << value ;
std::cout << '\n' ;
}
// create a matrix with each element as a pair
// pair.first == value of the item in the original matrix
// pair.second == position of the item in the row of the original matrix
std::pair< double, std::size_t > value_pos_pairs[N][N] ;
for( std::size_t row = 0 ; row < N ; ++row )
for( std::size_t col = 0 ; col < N ; ++col )
value_pos_pairs[row][col] = { original_matrix[row][col], col+1 } ;
// col+1 to make the position one-based
for( auto& row : value_pos_pairs ) // for each row in value_pos_pairs
std::sort( row, row+N ) ; // sort the row on values
// print out the sorted pairs
std::cout << "\nsorted; number in parentheses is the (one-based) position "
"in the original matrix:\n" ;
for( const auto& row : value_pos_pairs ) // for each row in value_pos_pairs
{
for( const auto& pair : row ) // for each value-pos pair in the row
std::cout << std::setw(6) << pair.first << " (" << pair.second << ") " ;
std::cout << '\n' ;
}
}
|