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.