Actually there is a pretty neat solution for this with nested functions (which are an extension of GCC).
What you can do is make a general comparator:
int my_comparator(const void* a, const void* b, int n) { double da = ((double*)a)[n]; double db = ((double*)b)[n]; return (da > db) ? 1 : ((da < db) ? -1 : 0); }
and a custom sort function that wraps the original qsort()
:
void my_qsort(void* base, size_t num, size_t size, int (*comparator)(const void *, const void *, int), int field) { int my_qsort_comperator(const void* a, const void* b) { return comparator(a, b, field); } qsort(base, num, size, my_qsort_comperator); }
This function behaves the same as the original qsort()
, except that it requires an additional field
argument, which indicates the index of the field to sort.
source share