如何在 C/C++ 中对多维数组进行排序

How to sort multidimensional array in C/C++

本文关键字:数组 排序 C++      更新时间:2023-10-16

在多次尝试使用排序但没有成功之后,我的实际代码在这里:

#include <algorithm>
#define N   5

    int a[N] = { 3, 6, 2, 4, 1 }; 
    int b[N] = { 6, 3, 1, 2, 9 };
    int c[N][3];
    for ( size_t i = 0; i < N; i++ )
    {
        c[i][0] = a[i]; c[i][1] = b[i]; c[i][2] = i;
    }
    for ( size_t i = 0; i < N; i++ ) printf( "%d,%d, %dn", c[i][0], c[i][1], c[i][2] ); 

实际输出为:

3,6,0
6,3,1
2,1,2
4,2,3
1,9,4

我需要用第一个键排序,输出预期应该是这样的:

1,9,4
2,1,2
3,6,0
4,2,3
6,3,1

我尝试了一些绝望的sort(c, c + N);.

c-array 不可分配,因此不满足std::sort要求。

按照建议,在 C++11 中,您可以改用std::array

std::array<int, 3> c[5] = {
    {3, 6, 0},
    {6, 3, 1},
    {2, 1, 2},
    {4, 2, 3},
    {1, 9, 4}
};
std::sort(std::begin(c), std::end(c));

现场演示

使用 qsort 版本

#include <cstdio>
#include <cstdlib>
#define N   5
using namespace std;
int cmp(const void  *a, const void *b){
    int *x = (int*)a;
    int *y = (int*)b;
    return (*x > *y) - (*x < *y);
}
int main(){
    int a[N] = { 3, 6, 2, 4, 1 }; 
    int b[N] = { 6, 3, 1, 2, 9 };
    int c[N][3];
    for ( size_t i = 0; i < N; i++ )
    {
        c[i][0] = a[i]; c[i][1] = b[i]; c[i][2] = i;
    }
    qsort(c, N, sizeof(*c), cmp);
    for ( size_t i = 0; i < N; i++ ) printf( "%d,%d, %dn", c[i][0], c[i][1], c[i][2] ); 
}