82. Use the accepted idioms to really shrink capacity and really erase elements

Summary

Use a diet that works: To really shed excess capacity from a container, use the “swap trick.” To really erase elements from a container, use the erase-remove idiom.

Discussion

Some containers (e.g., vector, string, deque) can end up carrying around extra capacity that’s no longer needed. Although the C++ standard library containers provide no guaranteed way to trim excess capacity, the following “swap trick” idiom works in practice to get rid of excess capacity for such a c of type container:

container<T>( c ).swap( c ); // the shrink-to-fit idiom to shed excess capacity

Or, to empty c out completely, clearing all contained elements and shedding all possible ...

Get C++ Coding Standards: 101 Rules, Guidelines, and Best Practices now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.