【问题标题】:C++ 2D Array SortingC++ 二维数组排序
【发布时间】:2017-04-21 16:00:05
【问题描述】:

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

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

对于第 4 列:

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

【问题讨论】:

标签: c++ arrays sorting 2d


【解决方案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;
}

【讨论】:

  • 嗯,它并没有什么用处,在你添加示例之前应该是一个评论。
  • 另外,Comparate2DArrayByCollumn 不应该被模板化,而 operator() 应该被模板化。这样你就不需要Comparate2DArrayByCollumn&lt;double&gt;(2),而是可以使用Comparate2DArrayByCollumn(2)
  • 这仅考虑了第三列,那么第四列呢?
  • @biagio-festa 使用 std::sort(array.begin(), array.end(), Comparate2DArrayByCollumn(3);
  • @devalone 然后对(2)的排序将丢失:D
猜你喜欢
  • 1970-01-01
  • 2020-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-17
  • 1970-01-01
  • 2011-02-17
  • 2019-05-17
相关资源
最近更新 更多