Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,914 questions

51,847 answers

573 users

How to sort columns of a matrix according to a specific row in C++

2 Answers

0 votes
#include <iostream>
#include <algorithm>

#define COLS 4

int row_to_sort = 0; 
int matrix[COLS][COLS] = { {2, 8, 1, 4},
                           {7, 0, 9, 8},
                           {2, 1, 6, 3},
                           {3, 8, 5, 6} };

void print_matrix(int matrix[][COLS], int rows, int cols) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            std::cout << matrix[i][j] << " ";
        }
        std::cout << "\n";
    }
}

int main() {
    int col_indexes[COLS] = { 0 };
    for (int i = 0; i < COLS; i++) {
        col_indexes[i] = i;
    }
    
    std::sort(col_indexes, col_indexes + COLS, [] (const int &a, const int &b) { 
        return matrix[row_to_sort][a] < matrix[row_to_sort][b];
    });
    
    int result[COLS][COLS] = {{ 0 }}; 
    for (int i = 0; i < COLS; i++) {
        for (int j = 0; j < COLS; j++) {
            result[i][j] = matrix[i][col_indexes[j]];
        }
    }
    
    print_matrix(result, COLS, COLS);
}
 
   
   
    
/*
run:

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

*/

 



answered Mar 15, 2024 by avibootz
0 votes
#include <iostream>
#include <algorithm>

#define COLS 4

void print_matrix(int matrix[][COLS], int rows, int cols) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            std::cout << matrix[i][j] << " ";
        }
        std::cout << "\n";
    }
}

int main() {
    int matrix[COLS][COLS] = { {2, 8, 1, 4},
                               {7, 0, 9, 8},
                               {2, 1, 6, 3},
                               {3, 8, 5, 6} };
                           
    int col_indexes[COLS] = { 0 };
    for (int i = 0; i < COLS; i++) {
        col_indexes[i] = i;
    }
    
    int row_to_sort = 0; 
    std::sort(col_indexes, col_indexes + COLS, [&] (const int &a, const int &b) { 
        return matrix[row_to_sort][a] < matrix[row_to_sort][b];
    });
    
    int result[COLS][COLS] = {{ 0 }}; 
    for (int i = 0; i < COLS; i++) {
        for (int j = 0; j < COLS; j++) {
            result[i][j] = matrix[i][col_indexes[j]];
        }
    }
    
    print_matrix(result, COLS, COLS);
}
 
   
   
    
/*
run:

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

*/

 



answered Mar 15, 2024 by avibootz
...