facing problem in arrays2.0 in strings stl part my compare function is not running as well as i m not able to understand what bool compare(string a, string b) funct basically works
Arrays2.0 in string stl
Hi @anujkurmi, pls tell in what part you are facing in arrays 2. Is it a question or a concept or some code u have made which u have doubt in.
Also the compare function is used for comparator in the STL sort function. It is required when you want to sort something in a particular manner. By default we give only 2 parameters in sort function and it sorts that part of given entitiy vector for example in increasing order. But what if we want to sort it in decreasing order or if we want to sort numbers based on wether they are odd or even. Then the use of comparator comes in.
Lets take an example. We 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 compare for custom sortings. And you can give any name instead of compare, it’s just a variable name.
Hope this helps 