Call empty () instead of checking whether size () is 0

Source: Internet
Author: User
Zookeeper

For any container C, the Code if (C. Size () = 0) is essentially equivalent to If (C. Empty. In this case, why is it biased towards a certain form, especially considering that empty () is usually implemented as an inline function, and all it does is return whether the size () is 0.

The reason is simple: Empty () is a constant time operation for all standard containers, while size () takes linear time for some list implementations.

Cause: In all standard containers, only list has the ability to link elements from one place to another without copying any data. You can use constant time to link a range from one list to another, which provides efficient link operations. If size () is a constant time operation, each member function in the list must update the size of the linked list they operate on, including splice (for source code, see list source code ), however, the only way for splice to update the size of its changed linked list is to calculate the number of connected elements, which makes splice not have the expected constant time operation performance. If you do not require splice to update the size of the changed linked list, splice can be a constant time operation, but size () will become a linear time operation. Generally, it needs to traverse its entire data structure to see how many elements it contains. Therefore, list and splice must have a concession. However, no matter what happens, calling empty () instead of checking whether size () = 0 is true.

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.