You are not logged in. Please login at to post your questions!


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

Thanks in advance!

asked 26 Aug '14, 22:47

cute_girl's gravatar image

accept rate: 0%

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

answered 05 Sep '14, 21:26

saikatkumardey's gravatar image

accept rate: 50%

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

(11 Sep '14, 22:33) cute_girl1★
(26 Oct '14, 21:05) saikatkumardey2★

Well the general syntax of the sort() function is sort(start,end,overload function); 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;
    return as<bs;
  return a.f<b.f;

answered 27 Aug '14, 00:31

thechamp103's gravatar image

accept rate: 16%


answered 26 Oct '14, 21:47

dextrous's gravatar image

accept rate: 0%

toggle preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here



Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text]( "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported
  • mathemetical formulas in Latex between $ symbol

Question tags:


question asked: 26 Aug '14, 22:47

question was seen: 5,524 times

last updated: 26 Oct '14, 21:47