Problem with stl sort compare function

I was trying to solve this problem on spoj -

wherein my algorithm required to sort the array according to their ending times.(i.e One ending first must come before in the array).

This is what I tried-

But the code gives runtime eorror (SIGSEGV) on spoj.

Just to see if there was something wrong with my comparator function I now modified the code to this one-

(same logic but avoiding the use of the comparator function)
And this one got ACCEPTED!

what makes the first one go wrong??

Not sure if it can help you now (after so long), but here’s the fault (in case anyone else ever comes to this post having the same issue).

here is your solution modified a little bit to get accepted.

The key point to note is that bool cmp(type A, type B) should evaluate to A < B and not A <= B (your comparator does that). So if A == B, cmp(A, B) is same as cmp(B, A) which is contradiction. C++ sort does this kind of checks while sorting and when such a problem arises (probably some assert fails) it gives a runtime error.

P.S. Erritcho has talked about it a little bit in his exchange arguments video.

1 Like