Sort using comparator

bool compare(int a, int b)
{return a>b}

int arr[n]={1, 3, 2, 2, 7, 5, 4, 6}
sort(arr, arr+n, compare);

What arguments are passed to the compare function by the sort STL function? Is it the 1st and the 2nd element of the array?

Hello too!
Let me Google that for you…
Here you are: https://www.cplusplus.com/reference/algorithm/sort/
Have a nice day!

3 Likes

The compare function explains on which criteria you want your values to be ordered.
More precisely, given two values a and b, it must return if you consider that a must be ranked higher than b.
The default sort ranks a higher than b if a > b but you can imagine other possibilities:

  • rank a higher than b if a*a > b*b (sort by absolute value)
  • rank a higher than b if arr2[a] > arr2[b] where arr2 is another array
  • rank a higher than be if f(a) > f(b) where f is a function (f is called an “evaluation function” in this case)
2 Likes

Thank you Google… :roll_eyes:

2 Likes