Search code examples
ccomparesimgrid

SimGrid. How to write comparator?


I have a dynamic array of hosts:

xbt_dynar_t dynar_host = xbt_dynar_new(sizeof(MSG_host_t), NULL);

Each host contains information about its speed in flops. I want to sort it by their host's speed. In documentation I found function xbt_dynar_sort. This function accepts two parameters: dynamic array itself and comparator int_f_cpvoid_cpvoid_t compar_fn.

Any advises or example how can this comparator be written?


Solution

  • This function only apply the standard qsort function to the data stored in the dynar, so you should also read the libc documentation, the man page or this tutorial for more info.

    So you should write a function somehow similar to the following:

    int mycmp(void *a,void*b) 
    {
      MSG_host_t hostA = *(MSG_host_t*)a;
      MSG_host_t hostB = *(MSG_host_t*)b;
      double valA = MSG_host_get_speed(hostA);
      double valB = MSG_host_get_speed(hostB)
      return (valA > valB) - (valA < valB);
    }
    

    And then, call xbt_dynar_sort(dynar, mycmp) to sort your dynar.

    Note that the actual comparison on the return line of the function is a bit complicated. This is a way to obey the function semantic (return -1 if A < B, 0 if A==B and 1 if A > B) in a way that is numerically stable. This is as advised in the relevant documentation of libc.