Search code examples
c++vectorsetstdswap

Why and when to use clear()


According to this clear() will destroy all the objects, but will not free the memory. Also while I encountered the necessity of removing all elements of a set I found out that the time complexity of set.clear() is linear in size (destructions) whereas constant for set.swap(). (same problem while removing all elements of vector)

So isn't that we should always use swap() with an empty STL container whenever possible in such cases? Thus what is the need and benifits of clear() over swap with an empty container.

Sorry, if this seems trivial but I couldn't find anything regarding this. Thanks!


Solution

  • when to use clear()

    When you want to remove all elements of a container.

    why use clear()

    Because it is the clearest and most efficient way to achieve the above.

    clear() will destroy all the objects, but will not free the memory.

    This is a desirable feature. It allows clear to be fast, and allows addition of new elements into the container to be fast because memory has already been allocated.

    If you want to free the memory - knowing that you will need to pay again for the allocation if you insert new elements, you can use shrink_to_fit.

    I found out that the time complexity of set.clear() is linear in size (destructions) whereas constant for set.swap().

    You are forgetting that the previously empty, now full set has to be eventually destroyed. Guess what the complexity of the destructor of set is.

    It is linear in size of the set.

    So isn't that we should always use swap() with an empty STL container whenever possible in such cases?

    Swap introduces extra unnecessary operations which clear does not do, and is therefore not as efficient. Furthermore, it does not express the intent as clearly.

    There is no advantage in replacing clear with a swap in general case.


    Swapping with an empty container does have its uses in rare cases. For example, if you need to clear a container within a critical section, then swapping and leaving the destruction of elements later can allow reducing the size of that critical section.