What is the meaning of below statement?

bool comp(const pair<double,double> &a, const pair<double,double> &b)
{
   return (double)(a.first/a.second) > (double)(b.first/b.first);
}

1 Like

It means you are defining your own comparator, that is, compare function, which will be used to order(generally sort) your inbuilt container.

Suppose you have a vector of pair of int where each element of vector is of form (a,b). Let the vector be vec. So when you call :

sort(vec.begin(),vec.end(),comp);

the call sorts the vector in such a way that if a pair A appears before pair B in final sorted list,then

(double)(A.first/A.second) > (double)(B.first/B.first)

While comparing in internal sorting, this function is called with 2 objects of the container vec - A,B for this question to be answered - Is A supposed to go before B? and if after the computation it returns true, it means the answer to question is yes, otherwise no.

Simply, if you sort a vector of only int, then if your comp is returning true if :

a< b - the container will be sorted in ascending order

a> b - the container will be sorted in descending order

3 Likes

I think @ankesh18 misinterpret the question.

According to cplusplus, Comp is a Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool. The value returned indicates whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines.

Now if i redefine your function, then i can write it as

return (a.first > a.second) ;

So according to definition, it will sort the vector in descending order according to only pair vector a

For more info. you can refer example of cplusplus above link.

Feel free to ask again if u still have a doubt. :slight_smile:

@ankesh18 nicely explained!!

@bansal1232 I still dont understand how have I misinterpreted?

@ankesh18 You did not explain this statement in a correct way! But your explanation about how it works for other is nice… So you have to see other things also like *** return (a.first > a.second) ; ***

I wanted to explain just the working principal!

Is C++ STL Pair same as structure in C++?

Pair is also a structure(inbuilt). You can have pair of structures too.