STD: a trap in the sort function

Source: Internet
Author: User

A few days ago, I received a very serious bug in the game. When I executed an operation, it would become stuck. At the end of the debugging, locate the STD sort function and find that the function crashes as soon as it enters the debugging process. It is very likely that an endless loop occurs in it. At the beginning, I was surprised. Well-known, well-tested STLAlgorithmWill there be an endless loop? As a result, Baidu found many people on the Internet have encountered similar situations. Most of the endless loops occur because the comparison function in the sort function returns true for equal elements.

 

The sort function of STD uses the quicksort algorithm and uses piecewise recursive sorting. It is likely that a problem occurs during recursion, resulting in an infinite recursive loop. Later I sawThere are 21st items in keep Itve STL:Always let the comparison function return false for the same element.However, there is also a more safe way to use the stable_sort function, which is a stable sorting algorithm that maintains the order when two elements are equal. It is verified that this function will not cause an endless loop in any case. However, this function has a higher overhead than the sort function.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.