C 2D数组排序

C++ 2D Array Sorting

本文关键字:数组排序 2D      更新时间:2023-10-16

我正在尝试对2D数组中的元素进行类似的方式:

338 640 723.771 62.1603

364 804 882.56 65.642

199 664 693.179 73.3166

我需要对它们进行对第三列和第4列的疑问。

例如第三列:

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

使用STD ::与您自己的比较器进行排序。我会这样解决:

#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;
}