如何对2d向量的列进行排序?

问题描述 投票:-2回答:1

例如,此输入需要对每个列进行排序:

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

仅对最后一列进行排序

c++ matrix vector
1个回答
0
投票

尝试转置,然后对行进行排序,然后再次转置。

© www.soinside.com 2019 - 2024. All rights reserved.