【发布时间】:2020-08-16 00:23:15
【问题描述】:
每一列都需要排序,例如对于这个输入:
3 //3 by 3 matrix
2 3 4
34 3 1
4 54 2
输出应该是
2 3 1
4 3 2
34 54 4
这是我的代码:
cin >> n;
vector<vector<int>> A(n, vector<int>(n));
for (auto &row : A)
for (auto &el : row)
cin >> el;
for (int i = 0; i < n; i++)
sort(A.begin(), A.end(), [&](vector<int>& l, vector<int>& j) {
return (l[i] < j[i]);
});
for (auto row : A)
{
for (auto el : row)
cout << el << " ";
cout << "\n";
}
我的代码的问题是它对某些列进行了排序,但不是全部。请帮我解决它
如果我输入上面的第一个示例,我的输出是:
34 3 1
4 54 2
2 3 4
只有最后一列被排序
【问题讨论】:
-
你让事情变得比自己需要的更难。
vector<vector<int>>是一个数组数组。它不关心它的更高层次的含义是什么。如果你有一个列向量而不是行向量,那会容易得多。 -
@Frank 请举例说明
-
@MogovanJonathan -- 问题是该循环的每次迭代都会弄乱前一个排好序的列。至少,你应该已经看到并在你的帖子中提到它,或者注意到它并提出另一个设计。你必须改变你对
vector<vector<int>>含义的表示。