Discussion
Team LiB
Previous Section Next Section

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 capacity, the idiom is:



container<T>().swap( c );   // the idiom to shed all contents and capacity



In related news, a common surprise for new STL programmers is that the remove algorithm doesn't really remove elements from a container. Of course, it can't; an algorithm just works on an iterator range, and you can't actually remove something from a container without calling a container member function, usually erase. All remove does is to shuffle values around so that the elements that shouldn't be "removed" get shuffled up toward the beginning of the range, and return an iterator to one past the end of the unremoved elements. To really get rid of them, the call to remove needs to be followed by a call to erasehence the "erase-remove" idiom. For example, to erase all elements equal to value from a container c, you can write:



c.erase( remove( c.begin(), c.end() ,value ) );



Prefer to use a member version of remove or remove_if on a container that has it.

    Team LiB
    Previous Section Next Section