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

前端 未结 10 2393
我寻月下人不归
我寻月下人不归 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:57

    you can get seg fault but this is not for sure since accessing out of range elements of vector with operator[] after clear() called before is just undefined behavior. From your post it looks like you want to try if elements are destroyed so you can use at public function for this purpose:

    The function automatically checks whether n is within the bounds of valid elements in the vector, throwing an out_of_range exception if it is not (i.e., if n is greater or equal than its size). This is in contrast with member operator[], that does not check against bounds.

    in addition, after clear():

    All iterators, pointers and references related to this container are invalidated.

    http://www.cplusplus.com/reference/vector/vector/at/

提交回复
热议问题