使用STL Sort()对2-D数组进行排序
sort 2-d array using stl sort()
我有一个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;
}
相关文章:
- 显示错误输出的简单数组排序程序
- C 使用单个函数对具有多种值类型的数组排序
- 2D数组排序,空格打乱顺序
- C 2D数组排序
- C++数组排序 - 将"bbba"和"0001"视为不正确排序的问题
- 数组排序功能
- CString 数组排序
- 简单的数组排序/检查 划分和征服版本
- C++ 中的多维数组排序
- 选择在++中对并行数组排序
- C++:二维指针数组排序:选择排序不适用于某些实例
- C++字符串数组排序
- C++中的指针数组排序算法
- 在VC++6中使用向量进行数组排序时出错,而在VC++2012中没有错误
- 将索引数组排序为主数组
- 数组排序、数组输入、数组输出
- C++数组排序,内存错误
- 在嵌入式系统上将数组排序功能从c++移植到c
- 基于其他int数组排序
- 多维数组排序c++奇怪行为