使用 stl sort() 对二维数组进行排序 [英] sort 2-d array using stl sort()
问题描述
我有一个二维数组,只包含 0 或 1.我想使用 STL 排序算法按行(每列没有变化)按降序对其进行排序.但我不知道如何传递参数以及如何在 sort(first, last, comp) 中编写比较函数;喜欢:
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. but I don't know how to pass the parameter and how to write the compare function in sort(first, last, comp); like:
0 1 1 1
1 1 0 1
1 0 1 0
应该是这样排序的:
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(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.
推荐答案
你对 sort 的调用在我看来是错误的(尽管你从未说过 a
是什么).应该是 sort(table, table+row, compare_function)
Your call to sort looks wrong to me (though you never said what a
is). It should be sort(table, table+row, compare_function)
但无论如何我都会做一些不同的事情(std::lexicographical_compare
来自
):
But I'd do it a bit differently anyway (std::lexicographical_compare
comes from <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))
这篇关于使用 stl sort() 对二维数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!