【问题标题】:How to sort the column of a 2d vector? [closed]如何对二维向量的列进行排序? [关闭]
【发布时间】: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&lt;vector&lt;int&gt;&gt; 是一个数组数组。它不关心它的更高层次的含义是什么。如果你有一个列向量而不是行向量,那会容易得多。
  • @Frank 请举例说明
  • @MogovanJonathan -- 问题是该循环的每次迭代都会弄乱前一个排好序的列。至少,你应该已经看到并在你的帖子中提到它,或者注意到它并提出另一个设计。你必须改变你对 vector&lt;vector&lt;int&gt;&gt; 含义的表示。

标签: c++ matrix vector


【解决方案1】:

问题在于,对于 for 循环的每次迭代,std::sort 可能会更改已排序的列。

例如,如果您对列 i 进行排序,那么列 i-1i-2 等可能会丢失对这些列进行排序时所做的更改。

在不更改太多原始代码的情况下,尽管这不是最有效的方法,但您可以创建一个辅助 std::vector&lt;std::vector&lt;int&gt;&gt; 并将循环内每次迭代的排序列结果保存在辅助向量中。

循环完成后,将辅助向量分配回原始向量。

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

std::vector<std::vector<int>> A = {{2, 3, 4}, {34, 3, 1}, {4, 54, 2}};

int main()
{
    if ( !A.empty() && !A[0].empty() )
    {
        auto auxV = A; // The auxiliary vector<vector>

        for (size_t i = 0; i < A[0].size(); i++)
        {
            // Sort column i
            std::sort(A.begin(), A.end(), [&](vector<int>& l, vector<int>& j) {
                return (l[i] < j[i]); 
                });

            // Save the results of the sort of column i in the auxiliary vector  
            for (size_t j = 0; j < A.size(); ++j)
                auxV[j][i] = A[j][i];
        }
        A = auxV; // copy the results back to the original vector
   }

    // display results
    for (auto& row : A)
    {
        for (auto el : row)
            std::cout << el << " ";
        std::cout << "\n";
    }
}

输出:

2 3 1 
4 3 2 
34 54 4 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-11
    • 2016-11-22
    • 1970-01-01
    相关资源
    最近更新 更多