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

微笑、不失礼 提交于 2020-01-02 07:06:14

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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".




回答5:


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.




回答6:


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.



来源:https://stackoverflow.com/questions/6218591/c-stdvector-stdsort-infinite-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!