C++ erasing part of the end of a vector without reallocation

橙三吉。 提交于 2020-05-29 03:30:53

问题


Looking through the C++ vector documents, pop_back() is a function that will not cause a reallocation of the vector's data. However, this only works for removing one member of the vector. I am trying to find a way to erase multiple members from the end of a vector. Originally I thought I would call pop_back() in a small for loop but I was wandering if there was a more convenient function that would do this for me?

Edit: The Cplusplus vector erase() reference is not as clear as it should be as pointed out by juanchopanza. It is why I originally discarded using erase(). Erase afterall, works well.


回答1:


Use vector::erase. It will not reallocate memory.

If your erased range does not extend to the end of the container, it WILL re-locate the end elements. That means the ending elements will be moved to their proper spot in memory which likely incurs a data copy. That is not the same as a re-allocation of the backing store. If your ending element is myVector.end(), no relocation will need to occur.




回答2:


You can use member functions erase. The vector will not be reallocated because according to the C++ Standard, e.g. C++17 n4659 standard draft 26.3.11.5 [vector.modifiers] "vector modifiers":

iterator erase(const_iterator position);
iterator erase(const_iterator first, const_iterator last);

3 Effects: Invalidates iterators and references at or after the point of the erase.

The bold part of the quote means that the vector will not be reallocated.



来源:https://stackoverflow.com/questions/25004618/c-erasing-part-of-the-end-of-a-vector-without-reallocation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!