如何在c/c中基于特定索引对二维数组进行排序
How to sort a 2D array on the basis of a particular index in c/c?
假设有一个二维数组a:
A[3][3] = { {1 ,4 ,7},
{6 ,2 ,3},
{3 ,5 ,5}
}
我想对索引I排序(比如1)结果应该是
A[3][3] = { {6 ,2 ,3},
{1 ,4 ,7},
{3 ,5 ,5}
}
对0排序将导致
A[3][3] = { {1 ,4 ,7},
{3 ,5 ,5},
{6 ,2 ,3}
}
如何使用排序函数来做到这一点?
In C:
qsort from stdlib.h对任意长度和任意元素大小的数组进行排序,为了实现您想要的,我们需要为它提供这两个信息,长度是行的数量,元素大小是列的数量。
除了这些,它还需要知道如何比较元素,qsort需要一个带有int (*)(void *, void *)签名的函数指针。这个函数是用指向每个元素的指针来调用的,这将是每行中第一个数字的地址,现在我们只需要将所选的元素相互比较。qsort在 a ,对于A == B为零,对于A>B为大于零,这是通过A减去B实现的。因为有了指针,所以可以将它们强制转换为int*,并使用索引操作符相互比较所需的位置。
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
const int sort_element = 1;// Choose a value from 0 to the column width
int intcmp( const void *a, const void *b ){
const int *A = a;
const int *B = b;
return A[sort_element]-B[sort_element];
}
int main(){
int a[3][3] = {
{1 ,4 ,7},
{6 ,2 ,3},
{3 ,5 ,5}
};
qsort( a, 3, sizeof(int)*3, intcmp);
}
正如你所看到的,我们需要一个比较函数来对每个元素进行排序。
如果使用c++ 11:
对列(col
)执行如下排序:
int col = 1;
std::sort(A, A+3, [=](const int* a, const int* b)
{
return a[col] < b[col];
});
如果你正在使用c++(即c++ 11之前):
为less操作定义一个函子类型:
class column_less
{
int col;
public:
column_less(int col) : col(col) { }
bool operator()(const int* a, const int* b) const
{
return a[col] < b[col];
}
}
然后对列(col
)进行排序,如下:
int col = 1;
std::sort(A, A+3, column_less(col));
std::sort
文档
尝试qsort,我相信它是在stdlib.h排序指针到每一行的第一个元素。
假设您的数据类型为uint32_t
。然后,您希望将其视为对sizeof(uint32_t) * number_of_columns
的项进行排序。当你调用compare函数时,你将传递给它这么大的项。比较函数在它传递的内容(实际上是一行)中查看适当的元素,然后重新排序该行中的元素。
相关文章:
- 将值从二维数组输出到文本文件
- 在二维数组中查找最小值和最大值?
- 移动二维数组中的字符
- 如何正确填充在堆上分配的二维数组?
- 传递二维数组时出现问题
- 具有随机数的二维数组不会更改
- 如何在C++中获取二维数组中最少的一列数?
- C++ 将二维数组索引与条件语句中的函数值进行比较
- 有效地从文本文件中读取带有字符串索引的大型二维数组(矩阵)
- 使用已知值,如何找到二维数组的索引?
- 将一维数组的索引转换为二维数组
- 检查二维数组中的相邻索引
- 是否可以使用负索引访问二维数组
- 从二维数组中给定的索引中求对角线元素的和
- 从行指针访问二维数组的行索引
- 二维数组索引中的c++错误
- 带索引二维数组的逗号运算符
- 在二维数组中查找一个值的多个索引
- 如何在c/c中基于特定索引对二维数组进行排序
- 如何在c++中输出二维数组的偶数列索引并对其进行计算