Advertisement
anechka_ne_plach

Untitled

Feb 8th, 2022
209
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.20 KB | None | 0 0
  1. #include <inttypes.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <stdio.h>
  5.  
  6. typedef struct data {
  7.     int (*get_rank)(const struct data*);
  8.     int rank;
  9. } data;
  10.  
  11. int get_rank(const data* d) {
  12.     return (d->rank);
  13. }
  14.  
  15. int strcmp(const void * x1, const void * x2)
  16. {
  17.     data* t1 = (data*)x1;
  18.     data* t2 = (data*)x2;
  19.     return (t1->get_rank(t1) - t2->get_rank(t2));              
  20. }
  21.  
  22. typedef int (*comparator_t)(const void *, const void *);
  23.  
  24. comparator_t comp = strcmp;
  25.  
  26. void rank_sort(data* elements[], size_t size) {
  27.     qsort(elements, size, sizeof(data*), comp);
  28. }
  29.  
  30. enum {
  31.     syze = 3
  32. };
  33.  
  34. int main() {
  35.     data* a = malloc(sizeof(data));
  36.     a->get_rank = get_rank;
  37.     a->rank = 1;
  38.     data* b = malloc(sizeof(data));
  39.     b->get_rank = get_rank;
  40.     b->rank = 2;
  41.     data* c = malloc(sizeof(data));
  42.     c->get_rank = get_rank;
  43.     c->rank = 3;
  44.     data* els[] = {c, a, b};
  45.     for (int i = 0; i < syze; ++i) {
  46.         printf("%d ", els[i]->get_rank(els[i]));
  47.         fflush(stdout);
  48.     }
  49.     printf("\n");
  50.  
  51.     rank_sort(els, syze);
  52.  
  53.     // for (int i = 0; i < syze; ++i) {
  54.     //     printf("%d ", els[i]->get_rank(els[i]));
  55.     // }
  56.     // printf("\n");
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement