I ran across an issue whenever I was trying to sort a vector of objects that was resulting in an infinite loop. I am using a custom compare function that I passed in to the sort function.
I was able to fix the issue by returning false when two objects were equal instead of true but I don’t fully understand the solution. I think it’s because my compare function was violating this rule as outlined on cplusplus.com:
Comparison function object that,
taking two values of the same type
than those contained in the range,
returns true if the first argument
goes before the second argument in the
specific strict weak ordering it
defines, and false otherwise.
Can anyone provide a more detailed explanation?
The correct answer, as others have pointed out, is to learn what a “strict weak ordering” is. In particular, if
comp(x,y)is true, thencomp(y,x)has to be false. (Note that this implies thatcomp(x,x)is false.)That is all you need to know to correct your problem. The
sortalgorithm makes no promises at all if your comparison function breaks the rules.If you are curious what actually went wrong, your library’s
sortroutine probably uses quicksort internally. Quicksort works by repeatedly finding a pair of “out of order” elements in the sequence and swapping them. If your comparison tells the algorithm that a,b is “out of order”, and it also tells the algorithm that b,a is “out of order”, then the algorithm can wind up swapping them back and forth over and over forever.