读书人

怎的同时根据结构体数组中两个结构体成

发布时间: 2012-08-10 12:19:33 作者: rapoo

怎样同时根据结构体数组中两个结构体成员排序
怎样同时根据结构体数组中两个结构体成员排序

C/C++ code
struct m{    int year;    int month;        int income;        };

在键盘输入数据后根据年月顺序进行排序

输入2001 5 100
2003 9 200
2001 4 500
2003 6 300
排序后 2001 4 500
2001 5 100
2003 6 300
2003 9 200


[解决办法]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct date
{
int year;
int month;
int day;
};

static int comp(const void *p_lhs, const void *p_rhs)
{
const date *lhs = (const date *)p_lhs;
const date *rhs = (const date *)p_rhs;
return ((lhs->year < rhs->year) || ((lhs->year == rhs->year) && (lhs->month < rhs->month)));
}

int main()
{
int i;
date dts[5] = {
{1999, 5, 6},
{1998, 1, 6},
{1998, 4, 7},
{2000, 3, 4},
{2000, 6, 6}
};
qsort((void*)dts, 5, sizeof(date), comp);

for (i = 0; i < 5; i ++)
{
printf("%d-%d-%d\n", dts[i].year, dts[i].month, dts[i].day);
}

return 0;

}

读书人网 >C++

热点推荐