使用STL Sort()对2-D数组进行排序

sort 2-d array using stl sort()

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

我有一个2-D数组,仅包含0或1。我想使用STL排序算法在行上以降序(每列无更改)对其进行排序。但是我不知道如何传递参数以及如何以排序编写比较函数(首先,最后,comp);喜欢:

0 1 1 1
1 1 0 1
1 0 1 0

将以这样的排序:

1 1 0 1
1 0 1 0
0 1 1 1

我的数据结构就是这样:

int **table = 0;
table = new int *[row];
for(int i=0;i<row;i++)
table[i] = new int[column];

我只能像这样编写排序函数:

sort(a[0], a[0]+row, compare_function);
bool compare_function(int a[], int b[])
{
    int i =0;
    while(a[i]==0 ||a[i]==1)
    {
        if(a[i]>b[i])
            return true;
        else
            i++;
    }
    return false;
}

但行不通。有人能帮我吗?非常感谢。

您对排序的调用对我来说看起来不错(尽管您从未说过a是什么)。它应该是sort(table, table+row, compare_function)

,但无论如何我都会有所不同(std::lexicographical_compare来自<algorithm>):

struct compare_rows {
  const int cols;
  compare_rows(int cols_) : cols(cols_) {}
  bool operator()(const int a[], const int b[]) const {
    // a b reversed to give descending sort
    return lexicographical_compare(b, b+cols, a, a+cols);
    }
  };

并将其像:

sort(table, table+row, compare_rows(column))

将您的比较函数更改为:

bool comp(const int a[], const int b[]){
  int sum1 = std::accumulate(a, a + column, 0);
  int sum2 = std::accumulate(b, b + column, 0);
  return sum1 < sum2;
}