简体   繁体   中英

c++ std::vector std::sort infinite loop

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?

If you're looking for a detailed explanation of what 'strict weak ordering' is, here's some good reading material: Order I Say!

If you're looking for help fixing your comparison functor, you'll need to actually post it.

If the items are the same, one does not go before the other. The documentation was quite clear in stating that you should return false in that case.

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, then comp(y,x) has to be false. (Note that this implies that comp(x,x) is false.)

That is all you need to know to correct your problem. The sort algorithm makes no promises at all if your comparison function breaks the rules.

If you are curious what actually went wrong, your library's sort routine 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.

The actual rule is specified in the C++ standard, in 25.3[lib.alg.sorting]/2

Compare is used as a function object which returns true if the first argument is less than the second, and false otherwise.

The case when the arguments are equal falls under "otherwise".

A sorting algorithm could easily loop because you're saying that A < B AND B < A when they're equal. Thus the algorithm might infinitely try to swap elements A and B, trying to get them in the correct order.

Strict weak ordering means a < b == true and when you return true for equality its a <= b == true. This requirement is needed for optimality for different sort algorithms.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM