I have a simple data structure with two floats. I would like to sort using one of the values as a key (dist). g_array_sort
isn’t returning the expected output
$ ./sort
Before:
d: 1.200000, dot: 3.200000
d: 0.400000, dot: 4.200000
d: 2.400000, dot: 0.200000
d: 0.100000, dot: 0.300000
After:
d: 0.100000, dot: 0.300000
d: 1.200000, dot: 3.200000
d: 0.400000, dot: 4.200000
d: 2.400000, dot: 0.200000
I would expect
After:
d: 0.100000, dot: 0.300000
d: 0.400000, dot: 4.200000
d: 1.200000, dot: 3.200000
d: 2.400000, dot: 0.200000
The code is below:
#include <glib.h>
#include <math.h>
struct pair
{
gfloat dist;
gfloat dot;
};
static gint
cmppairdist (gconstpointer a, gconstpointer b)
{
const struct pair* _a = a;
const struct pair* _b = b;
return _a->dist - _b->dist;
}
gint main(gint argc, gchar *argv[]) {
GArray * pairs;
struct pair p;
struct pair *t;
pairs = g_array_new(FALSE, FALSE, sizeof(struct pair));
p = (struct pair){ 1.2f, 3.2f };
g_array_append_val(pairs, p);
p = (struct pair){ 0.4f, 4.2f };
g_array_append_val(pairs, p);
p = (struct pair){ 2.4f, 0.2f };
g_array_append_val(pairs, p);
p = (struct pair){ 0.1f, 0.3f };
g_array_append_val(pairs, p);
g_print("Before:\n");
for(size_t n = 0; n < pairs->len; n++)
{
t = &g_array_index(pairs, struct pair, n);
g_print("d: %f, dot: %f\n", t->dist, t->dot);
}
g_array_sort(pairs, cmppairdist);
g_print("\nAfter:\n");
for(size_t n = 0; n < pairs->len; n++)
{
t = &g_array_index(pairs, struct pair, n);
g_print("d: %f, dot: %f\n", t->dist, t->dot);
}
g_array_free(pairs, TRUE);
return 0;
}
What I’m doing wrong? Any other coding hints?