Search code examples
c++sortingstlcomparatorarr

How Comparator Works Internally?


#include <iostream>
#include<bits/stdc++.h>
using namespace std;

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

int main() 
{
    int arr[5]= {1,2,5,9,6};
    sort (arr,arr+5, compare);
    
    for (auto i: arr)
    cout << i << " ";

    return 0;
}

The above code is sorted in descending order. I am completely blank on how it is working. I read articles but did not get a good explanation.

  1. Why compare is not followed by () while calling as we do with functions?
  2. How does the compare function get the value as we do not have passed any parameters?
  3. How do return true and false results in descending order sorting?

Solution

    1. Because you are not calling it. You are passing the compare function to std::sort without calling it, so that std::sort can call it for you.

    2. It is called by std::sort (many times), and std::sort supplies the parameters from your array

    3. Again std::sort looks at the return value (true or false) and sorts the two numbers accordingly.