首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

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

2012-08-10 
怎样同时根据结构体数组中两个结构体成员排序怎样同时根据结构体数组中两个结构体成员排序C/C++ codestruc

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

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;

}

热点排行