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

×

# How to use compare function in sort()

 0 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 31●2●4 accept rate: 0%

 2 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 136●1●4●5 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) 1 Please refer this link: http://www.cplusplus.com/reference/cstdlib/qsort/ (26 Oct '14, 21:05)
 2 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 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
 0 answered 26 Oct '14, 21:47 5★dextrous 158●2●2●10 accept rate: 0%
 toggle preview community wiki:
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