Why doesn't vector::clear remove elements from a vector?

前端 未结 10 2498
我寻月下人不归
我寻月下人不归 2020-11-29 07:29

When I use clear() on a std::vector, it is supposed to destroy all the elements in the vector, but instead it doesn\'t.

Sample

10条回答
  •  难免孤独
    2020-11-29 07:42

    try to access to an elements sup than 4 that you use for constructor may be you will get your segmentation fault An other idea from cplusplus.com:

    Clear content

    Removes all elements from the vector (which are destroyed), leaving the container with a size of 0.

    A reallocation is not guaranteed to happen, and the vector capacity is not guaranteed to change due to calling this function. A typical alternative that forces a reallocation is to use swap:

    vector().swap(x); // clear x reallocating

提交回复
热议问题