C ++ 2D数组排序

时间:2017-04-21 16:00:06

标签: c++ arrays sorting 2d

我试图像这样对二维数组中的元素进行排序:

  

338 640   723.771   62.1603

     

364 804   882.56   65.642

     

199 664   693.179   73.3166

我需要对第3和第4列进行排序。

例如第3栏:

  

199 664 693.179 73.3166

     

338 640 723.771 62.1603

     

364 804 882.56 65.642

第四栏:

  

338 640 723.771 62.1603

     

364 804 882.56 65.642

     

199 664 693.179 73.3166

我希望我能解释一下我想做什么。谢谢你的帮助..

答案:

我找到了需要的东西。我把代码放在这里也许它可能对其他人有帮助。

这是列的比较函数:

bool Compare(vector<double> A, vector<double> B) {
    return (A[2] < B[2]); // 2 means which column that you want to compare

}

这是排序代码:

std::sort(dots.begin(), dots.end(), &Compare); // "dots" needs to be a vector. in this case its a 2d double vector

来源是:https://stackoverflow.com/a/37516971/5331586

1 个答案:

答案 0 :(得分:-1)

将std :: sort与您自己的比较器一起使用。我会这样解决:

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

using std::cout;
using std::cin;
using std::endl;

class Comparate2DArrayByColumn {
public:
    Comparate2DArrayByColumn(int column)
        : column(column)
    {
    }
    template <typename T>
    bool operator()(const std::vector<T>& array1, const std::vector<T>& array2)
    {
        // do not use [] here, it will be UB
        return array1.at(column) > array2.at(column);
    }

private:
    int column;
};

void printArray(const std::vector<std::vector<double> >& array)
{
    for (auto& line : array) {
        for (auto val : line) {
            cout << val << " ";
        }
        cout << endl;
    }
}

int main()
{
    std::vector<std::vector<double> > array = {
        { 33, 640, 723.771, 62.1603 },
        { 364, 804, 882.56, 65.642 },
        { 199, 664, 693.179, 73.3166 },
    };

    printArray(array);
    cout << endl
         << endl;

    std::sort(array.begin(), array.end(), Comparate2DArrayByColumn(2));

    printArray(array);

    return 0;
}
相关问题