C Collections

cvector · Section 3

cvec_sort_with

cvec_sort_with - sort vector with custom comparison

C Collections (libccollections, -lccollections)

#include <ccollections/cvector.h>
 
cvec_sort_with(v, comparison_proc);

Sorts the vector in place through the csort library with a custom
comparison function, which follows the standard comparator convention of
returning a value <0, 0 or >0.
 
This is the supported way to sort a vector whose element type has no
default comparison procedure, that is the element types for which
cvec_sort refuses to compile: A struct, a union, a pointer to anything
other than char, and a fixed-size char array. It sorts a type that does
have a default comparison procedure as well, and then the procedure you
pass defines the order.

v                 Vector to sort. The macro evaluates it exactly once.
comparison_proc   Comparison function for sorting. The macro evaluates it
                  exactly once.

The sort is the stable, in-place mergesort of csort, which moves the
elements inside the backing array directly with no call per element
access. It takes O(n log n) time and O(n) space. Asserts if v is NULL.
 
A NULL comparison_proc makes it call ccol__fatal_err(). The comparison
procedure comes from the caller's own expression, whose value in general
isn't known before the program runs, so this is a run-time check. The
element-type check of cvec_sort is a compile-time _Static_assert
instead, and a cvec_sort call never gets to this diagnostic.
 
If the internal temporary buffer of the sort can't be allocated, the
macro calls ccol__fatal_err(), as every other type-inferred macro in
cvector.h that changes a vector does (cvec_push, cvec_reserve,
cvec_append_array and the others). The vector is then left completely
unsorted.

int compare_ints(const void *a, const void *b) {
  int x = *(const int *)a, y = *(const int *)b;
  return (x > y) - (x < y);
}
cvec_construct(vec, int);
// ... add elements ...
cvec_sort_with(vec, compare_ints);
cvec_destroy(vec);

cvec_sort(3), csort_sort(3)