My Question is related to this as I solved the problem, I wrote my own sorting algorithm (a simple insertion sort), and it works. I am quite surprised by this as I thought that the standard library is well-tested. Are there any known special cases in which std::sort
might mess up?
Asked
Active
Viewed 913 times
0
-
If your comparator is not self-consistent, then you could run into trouble. – Jonathan Leffler Oct 07 '11 at 20:40
-
what do you mean by self-consistent? – Sim Oct 07 '11 at 20:41
-
1If your comparator does not give a consistent answer when called with (a, b) and (b, a), you can run into trouble. If (a, b) returns true, then (b, a) had better return false. – Jonathan Leffler Oct 07 '11 at 20:45
-
2Note, too, that it is a mark of a tyro (newbie) to suggest there's a bug in a routine (template) used as extensively as `std::sort`. It is almost infinitely more probable that the problem is in the way you are using `std::sort` than that you've managed to find a problem (bug) in it. – Jonathan Leffler Oct 07 '11 at 20:46
-
You have the error. I have been in your place before but I was always wrong :).. – FailedDev Oct 07 '11 at 20:53
-
Yes you are right, the topic-header wasn't good, i modified it to make the context clearer. – Sim Oct 07 '11 at 21:02
-
2If you want to get an actual _fix_ for your problem, you need to post the code for your comparator. – ildjarn Oct 07 '11 at 21:04
2 Answers
6
No, it's highly unlikely that there are any known bugs in any of the common C++ standard library implementations of std::sort
. It's rigorously tested.
If you see a crash or incorrect results, it's almost certainly because you didn't adhere to the contract: either you passed in invalid arguments, or your comparator does not obey the requirements for a strict weak ordering (irreflexivity, asymmetry, transitivity, and transitivity of equivalence).

Adam Rosenfield
- 390,455
- 97
- 512
- 589
1
If your comparison function/object doesn't follow a strict weak ordering, or the thing you're sorting contains pointers that are no longer valid, either of those could cause it to break.

Mark B
- 95,107
- 10
- 109
- 188
-
well my algorithm doesn't tolerate nullpointer either, so the only possibility could be the second scenario, but I am not sure what exactly is meant by 'self consistent' – Sim Oct 07 '11 at 20:44
-
@Sim: It shouldn't be possible that `a < b` and `b < a` are both true. – UncleBens Oct 07 '11 at 21:31