如何在c/c中基于特定索引对二维数组进行排序

How to sort a 2D array on the basis of a particular index in c/c?

本文关键字:二维数组 索引 排序 于特定      更新时间:2023-10-16

假设有一个二维数组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函数时,你将传递给它这么大的项。比较函数在它传递的内容(实际上是一行)中查看适当的元素,然后重新排序该行中的元素。