Просто повторяйте, используя ссылку, а не копию при вызове 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;
}