Mogovan Jonathan
Mogovan Jonathan

Reputation: 173

How to sort the row of a 2d matrix?

this is my code

cin >> n;

    vector<vector<int>> A(n, vector<int>(n));

    for (auto &row : A)
        for (auto &el : row)
            cin >> el;

    for (auto row : A)
        sort(row.begin(), row.end());

    for (auto row : A)
    {
        for (auto el : row)
            cout << el << " ";
        cout << "\n";
    }

for example if the input is :

3 ///3 by 3 matrix
1 2 3
2 1 3
3 2 1

the output should be:

1 2 3 
1 2 3
1 2 3

my code gives me the same input and i don t know how to fix it.

Upvotes: 0

Views: 230

Answers (2)

brc-dd
brc-dd

Reputation: 12964

Just iterate using reference, not a copy while calling std::sort. Also, while printing it is better to use the reference as copying each row incurs a penalty of O(n), where n is the number of elements in that row.

Here is the code:

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std; // this is not a good practice.

int main() {
    int n; 
    cin >> n;
    vector<vector<int>> A(n, vector<int>(n));
    for (auto &row : A)
        for (auto &el : row)
            cin >> el;
    for (auto &row : A) //change this line
        sort(row.begin(), row.end());
    for (auto &row : A)
    {
        for (auto &el : row)
            cout << el << " ";
        cout << "\n";
    }
    return 0;
}

The asker has asked me to provide the code to sort the matrix by column. Here is the code:

#include <iostream>
#include <algorithm>
#include <vector>

void input_matrix(auto &x) {
    for (auto &i : x)
        for (auto &j : i)
            std::cin >> j;
}

void output_matrix(auto &x) {
    for (auto &i : x) {
        for (auto &j : i)
            std::cout << j << " ";
        std::cout << std::endl;
    }
}

void transpose_matrix(auto &x) {
    size_t n = x.size();
    for (size_t i = 0; i < n; i++)
        for (size_t j = i + 1; j < n; j++)
            std::swap(x[i][j], x[j][i]);
}

void sort_matrix_by_row(auto &x) {
    for (auto &i : x)
        std::sort(i.begin(), i.end());
}

void sort_matrix_by_col(auto &x) {
    transpose_matrix(x);
    sort_matrix_by_row(x);
    transpose_matrix(x);
} 

int main() {
    int n;
    std::cin >> n;
    std::vector<std::vector<int>> A(n, std::vector<int>(n));
    input_matrix(A);
    sort_matrix_by_col(A);
    output_matrix(A);
    return 0;
}

Upvotes: 2

john
john

Reputation: 87959

Like this

for (auto& row : A)
    sort(row.begin(), row.end());

You are trying to change the rows, so you need a reference to the original row. Your code is just sorting a copy of the row.

Upvotes: 2

Related Questions