Как отсортировать строку 2d матрицы? - PullRequest
1 голос
/ 01 мая 2020

это мой код

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";
    }

например, если ввод:

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

вывод должен быть:

1 2 3 
1 2 3
1 2 3

мой код дает мне тот же ввод, и я не знаю, как это исправить.

Ответы [ 2 ]

3 голосов
/ 01 мая 2020

Вот так

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

Вы пытаетесь изменить строки, поэтому вам нужна ссылка на исходную строку. Ваш код просто сортирует копию строки.

2 голосов
/ 01 мая 2020

Просто повторяйте, используя ссылку, а не копию при вызове std::sort. Кроме того, при печати лучше использовать ссылку, поскольку при копировании каждой строки налагается штраф O(n), где n - количество элементов в этой строке.

Вот код:

#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;
}

Запрашивающий попросил меня предоставить код для сортировки матрицы по столбцам. Вот код:

#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;
}
...