Function

GLibPtrArraysort_with_data

Declaration

void
g_ptr_array_sort_with_data (
  GPtrArray* array,
  GCompareDataFunc compare_func,
  gpointer user_data
)

Description

Like g_ptr_array_sort(), but the comparison function has an extra user data argument.

Note that the comparison function for g_ptr_array_sort_with_data() doesn’t take the pointers from the array as arguments, it takes pointers to the pointers in the array.

Use g_ptr_array_sort_values_with_data() if you want to use normal GCompareDataFuncs, otherwise here is a full example of use:

typedef enum { SORT_NAME, SORT_SIZE } SortMode;

typedef struct
{
  gchar *name;
  gint size;
} FileListEntry;

static gint
sort_filelist (gconstpointer a, gconstpointer b, gpointer user_data)
{
  gint order;
  const SortMode sort_mode = GPOINTER_TO_INT (user_data);
  const FileListEntry *entry1 = *((FileListEntry **) a);
  const FileListEntry *entry2 = *((FileListEntry **) b);

  switch (sort_mode)
    {
    case SORT_NAME:
      order = g_ascii_strcasecmp (entry1->name, entry2->name);
      break;
    case SORT_SIZE:
      order = entry1->size - entry2->size;
      break;
    default:
      order = 0;
      break;
    }
  return order;
}

...
g_autoptr (GPtrArray) file_list = NULL;
SortMode sort_mode;

// initialize file_list array and load with many FileListEntry entries
...
// now sort it with
sort_mode = SORT_NAME;
g_ptr_array_sort_with_data (file_list,
                            sort_filelist,
                            GINT_TO_POINTER (sort_mode));

This is guaranteed to be a stable sort since version 2.32.

This function is not directly available to language bindings.

Parameters

array

Type: An array of gpointer

A GPtrArray.

The data is owned by the caller of the function.
compare_func

Type: GCompareDataFunc

Comparison function.

user_data

Type: gpointer

Data to pass to compare_func.

The argument can be NULL.
The data is owned by the caller of the function.