Advertisement
kyoo0000

example_list

Sep 22nd, 2021
1,495
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.81 KB | None | 0 0
  1. #include <stdbool.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. typedef struct {
  6.   void**  values;
  7.   size_t  len, capacity;
  8.   void*   minimum;
  9.   void*   maximum;
  10.   int     (*compare)(const void*, const void*);
  11. } ArrList;
  12.  
  13. ArrList* init_list(size_t capacity, int (*compare)(const void*, const void*)) {
  14.   ArrList *l = (ArrList*) calloc(1, sizeof(ArrList));
  15.   l->capacity = capacity;
  16.   l->len = 0;
  17.   l->values = (void**) calloc(capacity + 1, sizeof(void*));
  18.   l->values[capacity] = NULL;
  19.   l->compare = compare;
  20.   l->minimum = l->maximum = NULL;
  21.   return l;
  22. }
  23.  
  24. void add_value(ArrList *l, void *value) {
  25.   if(l->len == l->capacity) {
  26.     l->capacity += 100;
  27.     l->values = realloc(l->values, l->capacity *sizeof(void*));
  28.   }
  29.  
  30.   if(l->minimum == NULL || l->compare(l->minimum, value) > 0)
  31.     l->minimum = value;
  32.   if(l->maximum == NULL || l->compare(l->maximum, value) < 0)
  33.     l->maximum = value;
  34.  
  35.   l->values[l->len++] = value;
  36. }
  37.  
  38. void destroy_arrlist(ArrList *list, void (*destroy_value)(void* value)) {
  39.   for(int i = 0; i < list->len; i++)
  40.     destroy_value(*(list->values + i));
  41.   free(list);
  42. }
  43.  
  44. void walk(ArrList *l, void (*action)(void*)) {
  45.   for(void** i = l->values; *i != NULL; ++i)
  46.     action((*i));
  47. }
  48.  
  49. bool is_empty(ArrList *list) { return list->len == 0;}
  50.  
  51. typedef struct {
  52.   int a;
  53. } Test;
  54.  
  55. int compare_test(const void* a, const void* b) {
  56.   Test *x = (Test*) a;
  57.   Test *y = (Test*) b;
  58.   return (x->a - y->a);
  59. }
  60.  
  61. void show_test(void *t) {
  62.   printf("t-value::%d\n", ((Test*) t)->a);
  63. }
  64.  
  65. int main(void) {
  66.   Test t[] = {{.a = 3}, {.a = 2}, {.a = 1}};
  67.  
  68.   ArrList *l = init_list(3, compare_test);
  69.   add_value(l, &t);
  70.   add_value(l, &t[1]);
  71.   add_value(l, &t[2]);
  72.   qsort(l->values, l->len, sizeof(void*), compare_test);
  73.  
  74.   walk(l, show_test);
  75.  
  76.   return  EXIT_SUCCESS;
  77. }
  78.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement