对字符串年月日进行从小到大排序的c++代码
时间: 2023-04-12 11:00:22 浏览: 109
以下是对字符串年月日进行从小到大排序的C代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_DATE_LEN 11
int compare_dates(const void *a, const void *b) {
char *date1 = *(char **)a;
char *date2 = *(char **)b;
int year1, month1, day1;
int year2, month2, day2;
sscanf(date1, "%d-%d-%d", &year1, &month1, &day1);
sscanf(date2, "%d-%d-%d", &year2, &month2, &day2);
if (year1 != year2) {
return year1 - year2;
} else if (month1 != month2) {
return month1 - month2;
} else {
return day1 - day2;
}
}
int main() {
char *dates[] = {"2022-01-01", "2021-12-31", "2022-01-02", "2021-12-30"};
int num_dates = sizeof(dates) / sizeof(char *);
qsort(dates, num_dates, sizeof(char *), compare_dates);
for (int i = 0; i < num_dates; i++) {
printf("%s\n", dates[i]);
}
return 0;
}
```
这段代码使用了 `qsort` 函数来对字符串数组进行排序,排序的依据是年月日的大小关系。函数 `compare_dates` 用来比较两个日期字符串的大小,它首先将日期字符串解析成年月日三个整数,然后按照年、月、日的顺序比较它们的大小。最后,主函数中调用 `qsort` 函数对日期字符串数组进行排序,并输出排序后的结果。