【问题标题】:sort 2-d array using stl sort()使用 stl sort() 对二维数组进行排序
【发布时间】:2012-12-21 20:56:19
【问题描述】:

我有一个二维数组,只包含 0 或 1。 我想使用 STL 排序算法按行的降序对它进行排序(每列没有变化)。但我不知道如何传递参数以及如何在 sort(first, last, 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;
}

但它不起作用。有人能帮我吗? 非常感谢。

【问题讨论】:

  • 这不是真的吗? [i]==0 ||a[i]==1 (除了当您在数组的定义区域之外读取时,在这种情况下内容完全未定义 - 在您到达内存中导致程序崩溃的位置之前,可能会连续出现大量零! )
  • 0 1 1 11 1 0 1 ??那不是排序

标签: c++ sorting stl


【解决方案1】:

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

但无论如何我都会做一些不同的事情(std::lexicographical_compare 来自 &lt;algorithm&gt;):

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))

【讨论】:

  • 谢谢,这就是我想要的。
【解决方案2】:

将比较函数更改为:

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

【讨论】:

  • 这没有降序,也没有按字典顺序排序(根据他的例子,这就是他想要的)
  • 你是对的。虽然我可以反转比较以给出降序,但它不一定按字典顺序排序
猜你喜欢
  • 1970-01-01
  • 2017-03-31
  • 1970-01-01
  • 1970-01-01
  • 2013-12-16
  • 1970-01-01
  • 2019-06-09
  • 1970-01-01
  • 2013-08-17
相关资源
最近更新 更多