How is it actually working
bool compare(string a,string b)
{
return a.length()>b.length()
}
Passing a custom comparison function in sort method
Hello @dare_devil_007,
You have seen writing return (a<b)/ or return a>b;
Did you ever bother what are they doing?
What are they returning?
What is its significance?
Let’s understand this with an example:
suppose you have to sort an array in increasing order.
Your compare() function is accepting two parameters a and b.
and you have written return a<b;
then the statement would return true if a is smaller than b.
So, sort() function will place a before b.
and in case of false(when a is greater than b)
The sort() function would place b before a.
Same is the case for decreasing order.
Hence, concluding:
true indicates that a should be placed before b in the sorted order.
and false indicates that a should be placed after b in the sorted order.
So, the function you have specified is sorting strings based on their lengths rather than their Lexicographic order.
Hope, this would help.
Give a like if you are satisfied.
Thanks a lot Vierender