繁体   English   中英

使用std :: sort对具有特定条件的2D向量进行排序

[英]Sorting a 2D vector with specific criteria using std::sort

我遇到了一个编码问题,涉及使用库algorithm std::sort使用所需标准对2D向量(矩阵)进行std::sort

例如,假设我有一个2D矢量

1,8,3
1,9,1
1,4,2 
    ^

我想按第三列对其进行排序(例如,增长标准),所以在排序之后,我想要一个矩阵:

1,9,1
1,4,2
1,8,3
    ^

我知道,为了在std::sort指定排序标准,需要在std::sort发送第三个函数。 如果它是一维vector那将不是问题。 我将在带有2个参数的std::sort内部创建一个lambda,将它们进行比较并返回true / false。

因此,现在您可以看到我面临的问题,如何访问矩阵中的特定元素(在我的情况下为第三列元素)并将其与std::sort进行比较?

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

void printMatrix(std::vector<std::vector<int>> m) {
    for(int i = 0; i < m.size(); i++) {
        for(int j = 0; j < m[i].size(); j++) {
            std::cout << m[i][j] << " ";
        }
        std::cout << std::endl;
    }
}

int main() {
    std::vector<std::vector<int>> m{
        {1,8,3},
        {1,9,1},
        {1,4,2}
    };

    std::sort(m.begin(), m.end(), [](int a, int b) { // error
                // ???
    });
    printMatrix(m);

    return 0;
}

我不想使用任何其他外部库来解决此问题。

任何帮助都非常感谢! :)

std::sort(m.begin(), m.end(), [](int a, int b) { // error
                // ???
    });

m.begin()m.end()返回的迭代器的value_typestd::vector<int> 因此,您的lambda的两个参数都需要采用该类型

std::sort(m.begin(), m.end(), 
        [](const std::vector<int>& a, const std::vector<int>& b) {
               return a.at(2) < b.at(2);
    });

注意:如果您错误地尝试按无效索引进行排序,则在这里使用at()成员函数而不是operator []来防止UB。

演示

当您要对std::vector<std::vector<int>>进行排序时,容器的项目类型为std::vector<int> ,而不是int 因此,您不能在声明中使用lambda

[](int a, int b) { ... }

对这样的容器进行分类。 您需要在声明中使用lambda

[](std::vector<int> a, std::vector<int> b) { ... }

要么

[](std::vector<int> const& a, std::vector<int> const& b) { ... }

使用第一个版本很昂贵,因为最终会为每个lambda调用复制std::vector 因此,建议使用第二个版本。

std::sort(m.begin(), m.end(), [](std::vector<int> const& a,
                                 std::vector<int> const& b) {
   return a.back() < b.back();
});

尽管这不是最有效的解决方案,但最简单的方法是将2D向量(也称为矩阵)转置,然后对每个向量排序。 这是一个经过测试的工作功能,可以为您完成此任务:

template<typename T>
void sortColumns(vector<vector<T> > &v){
    vector<vector<T> > rv(v[0].size(), vector<T>(v.size()));
    for(int i = 0; i < v.size(); i++){
        for(int j = 0; j < v[i].size(); j++){
            rv[j][i] = v[i][j];
        }
    }
    for(int i = 0; i < rv.size(); i++){
        sort(rv[i].begin(), rv[i].end());
        for(int j = 0; j < rv[i].size(); j++){
            v[j][i] = rv[i][j];
        }
    }
}

同样,这不是按列对矩阵进行排序的最有效或最现代的方法,但它有效且易于理解。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM