You are not logged in. Please login at www.codechef.com 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

1★cute_girl
3124
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
    }
link

answered 05 Sep '14, 21:26

saikatkumardey's gravatar image

2★saikatkumardey
136145
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★
1
(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;
  if(as!=bs)
    return as<bs;
  return a.f<b.f;
}
link

answered 27 Aug '14, 00:31

thechamp103's gravatar image

3★thechamp103
597411
accept rate: 16%

link

answered 26 Oct '14, 21:47

dextrous's gravatar image

5★dextrous
1582210
accept rate: 0%

toggle preview
Preview

Follow this question

By Email:

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

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "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:

×1,664
×74
×4

question asked: 26 Aug '14, 22:47

question was seen: 5,524 times

last updated: 26 Oct '14, 21:47