# How to use compare function in sort()

I have seen compare function in sort to sort using the second element and all! But i am not understanding the syntax. Can anyone please provide the syntax to sort the pairs by the sum of the elements or product of the elements so that i will get the idea of the compare function

Well the general syntax of the sort() function is
where the â€śoverload functionâ€ť is the one we provide to overload the original function of the c++.
As for sorting by sum or product just write a overload function as:

``````typedef pair<int,int> ii;
#define first f
#define s second
bool cmp(ii a,ii b)
{
int as=a.f+a.s,bs=b.f+b.s;
if(as!=bs)
return as<bs;
return a.f<b.f;
}``````
5 Likes

struct _pair
{
int first, second;
};

``````    /*in order to sort an array of _pair in increasing order based on the sum/product of the elements of _pair write a compare function like this.. The value returned (either 1 or 0) indicates whether the element passed as first argument is considered to go before the second.... */

int compare(const _pair& x, const _pair& y)
{
return (x.first+x.second) < (y.first+y.second); //modify it for sorting by product of elements
}``````
2 Likes

Suppose if i can use only qsort() where should i give compare as the argument in the function call? If C++ is blocked in a contest with only C/JAVA

1 Like