Comparator in sort()

I don’t have a complete idea of how it works , except that we can sort the vector according to a need. , but i cant understand its working

Hey @akshpreetsinghs
Every sorting algorithm have a comparison somewhere ,for ecample in bubble sort

for(...)
   for(...) 
      if(a[i]>a[i+1)swap 

Now this comparison is swapped by compre function which we define
And its defined as such that if it returns true then first argument we passed comes before 2nd args
or otherwise second before first if false

Hey just saw your chat, please continue here only
So assume this compare function

bool compare(int a,int b){
    if(a>b)return true;
    else return false; 
} 

Now we wanted to place a before b if its greater so this will arrange in descending order
You can write above compare alternative as

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

This will also return true when a>b else false
So see the condition according to which we want to sort is written inside compare function

Now assume u want to sort array of strings according to their length and if they are equal then acc to dictionary order

bool compare(string a,string b){
     if(a.length()>b.length()) return true;   //we want to place a first here
     else if(b.length()>a.length())return false;   //we want to place b first in this case
     else {
           if(a<b)return true; //a before b
           else return false; //b before a
    }
    
}

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.