简体   繁体   English

使用stl sort()排序二维数组

[英]sort 2-d array using stl sort()

I have a 2-d array, containing only 0 or 1. I want to sort it in descend order on rows (no change on each column) using STL sort algorithm. 我有一个二维数组,仅包含0或1。我想使用STL排序算法对行进行降序排序(每列均无变化)。 but I don't know how to pass the parameter and how to write the compare function in sort(first, last, comp); 但我不知道如何传递参数以及如何在sort(first,last,comp);中编写比较函数; like: 喜欢:

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

would be sorted like this: 会像这样排序:

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

my data structure is like this: 我的数据结构是这样的:

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

I can only write the sort function like this: 我只能这样写sort函数:

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

But it doesn't work. 但这是行不通的。 Can some one help me? 有人能帮我吗? Thank you very much. 非常感谢你。

Change your compare function to: 将您的比较功能更改为:

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

Your call to sort looks wrong to me (though you never said what a is). 您的排序请求对我来说似乎是错误的(尽管您从未说过a是什么)。 It should be sort(table, table+row, compare_function) 它应该是sort(table, table+row, compare_function)

But I'd do it a bit differently anyway ( std::lexicographical_compare comes from <algorithm> ): 但是无论如何我还是会做一些不同的事情( 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);
    }
  };

And use it like: 并像这样使用它:

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

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

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