Comparators - inbuilt sort function

The pdf given on comparators (in inbuilt sort function) doesn’t explain how it works for strings, the code for vector sorting is given under the string heading so can I get some help with that?

Hi Ishita, when we talk of ususal sorting / sorting in ascending order then we must know that value of captial letters is samller than that of lower case i.e.

‘A’ < ‘a’

and the value of the next letter is bigger than previous one i.e.

‘A’ < ‘B’

Now consider a vector arr which contains strings then:

sort(arr.begin(),arr.end()) ;
will sort the array with priorities/rules as above stated.

But if you want to sort them in some special order (decreasing or maybe process them a bit and then decide increase or decrease) then you can use comparator function.

Consider an example. If you are given a vector of strings and you have to sort the strings in increasing order but only on basis of every strings second character then you can do this:



bool compare( string x, string y ) {
return x[1] < y[1] ;
}


//somewhere in main or in any other function
sort( arr.begin(), arr.end(), compare ) ;

Hence you can use comparator for custom sortings.

Hope this helps :slight_smile:

Hey Ishita,
As you are not responding to this thread, I am marking your doubt as Resolved for now. Re-open it if required.

Please mark your doubts as resolved in your course’s “ Ask Doubt ” section, when your doubt is resolved.