Pregunta

I am using glib to sort:

gint cmp_values_by_attr1(gpointer a, gpointer b) {
   my_strcut *seq_a = *((my_strcut**) a);
   my_strcut *seq_b = *((my_strcut**) b);
   return (seq_a->attr1 - seq_b->attr1);
}
values = g_ptr_array_sized_new(4);
v = new_struct();
g_ptr_array_add(values, v);
...
g_ptr_array_sort(values, (GCompFunction) cmp_values_by_attr1);

Now inside my array, I would like to sort first by attr1 and then by attr2. How to implement?

¿Fue útil?

Solución 2

I have used some 'hack' to implement this sorting.

  • Make the two attributes to sort to be uint32_t types.
  • Add another attribute uint64_t for_sort to my struct
  • Shift the upper 32 bits of for_sort to be attr1
  • The lower 32 bits of for_sort to be attr2
  • Sort the array by for_sort, then the items are first sorted by attr1, then by attr2.

I have implemented and verified that it is working.

Disadvantages:

  • Extra memory to add for_sort
  • Extra processing
  • If the sorting attributes are in other types, need to change accordingly.

Otros consejos

It's quite simple—the comparison function returns less than, equal to, or greater than zero depending on whether the first value is less than, equal to, or greater than the second value. All you need to do is compare the first attributes and if the return value is not equal to zero return the result, otherwise compare the second attributes and return the result:

gint comp_values (gpointer a, gpointer b) {
  gint res;
  my_strcut *seq_a = *((my_strcut**) a);
  my_strcut *seq_b = *((my_strcut**) b);

  res = seq_a->attr1 - seq_b->attr1;
  if (res == 0) {
    res = (seq_a->attr2 - seq_b->attr2);
  }
  return res;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top