我有一个整数数组,我需要对包含 unix 时间的数组进行排序。我打算使用 qsort 对其进行排序,这很简单。但是,我还有一个“字符串”数组,需要保持与整数数组相同的顺序。
因此整数数组中的位置 2 将对应于另一个数组中位置二的元素。
有没有使用 qsort 来维持这种关系?
最佳答案
这样做
#include <stdlib.h>
#include <stdio.h>
struct Data
{
long int time;
const char *string;
};
int
datacmp(const void *const x, const void *const y)
{
return ((struct Data *) x)->time - ((struct Data *) y)->time;
}
int
main(void)
{
struct Data array[] = {
{1234, "1234 Text"},
{1034, "1034 Text"},
{1041, "1041 Text"}
};
size_t count;
count = sizeof(array) / sizeof(array[0]);
for (size_t i = 0 ; i < count ; ++i)
{
fprintf(stderr, "Entry %zu:\n\ttime : %ld\n\tstring: %s\n\n",
i, array[i].time, array[i].string);
}
fprintf(stderr, "\n");
qsort(array, count, sizeof(array[0]), datacmp);
fprintf(stderr, "---- Sorted array:\n");
for (size_t i = 0 ; i < count ; ++i)
{
fprintf(stderr, "Entry %zu:\n\ttime : %ld\n\tstring: %s\n\n",
i, array[i].time, array[i].string);
}
return 0;
}
关于c - 排序时保持两个数组的顺序相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35528921/