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