Use the "swap technique" to remove excess capacity

Source: Internet
Author: User
Zookeeper

When we need to delete some elements from the vector, we usually call erase in the form of intervals. This reduces the vector size but does not reduce its capacity. If your vector has 100,000 candidates at a certain time point, its capacity will remain at least 100000, even if there are only 10 elements later. To prevent the vector from occupying the memory that is no longer needed, we hope there is a way to reduce its capacity from the previous maximum to the current quantity. This capacity reduction is often referred to as "shrink to fit" (compressed to an appropriate size ). The method is as follows:

Vector <contestant> (contestants). Swap (contestants );

Expression Vector <contestant> (contestants) creates a temporary vector, which is a copy of contestants: this is done by the copy constructor of the vector. However, the copy constructor of the vector only allocates the required memory for the copied elements, so there is no extra capacity for this temporary vector. Then we perform swap operations on the data in the temporary vector and the data in contestants. After that, contestants has the removed capacity, that is, the capacity of the original temporary variable, the temporary variable capacity is changed to the original contestants bloated capacity. At the end of the statement, the temporary vector is destructed to release the memory occupied by contestants. The same technique applies to strings.

Note: During swap, not only are the content of the two containers exchanged, but their iterators, pointers, and reference pages are also exchanged (except for string ). After swap occurs, the iterator, pointer, and reference that originally points to an element in a container are still valid and point to the same element. However, these elements are already in another container.

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.