iterator erase ( iterator position );
iterator erase ( iterator first, iterator last );
Erase elements Removes from the vector container either a single element (position) or a range of elements ([first,last)).
This effectively reduces the vector size by the number of elements removed, calling each element's destructor before.
and:
remove
Removes all elements equaling the given value value from the range, defined by [first, last). Removing is done by shifting the elements in the range in such a way that required elements are overwritten. The elements between the old and the new ends of the range are left intact. Iterator to the new end of the range is returned.
Is there any way to remove elements from a std::vector within an iterator range(something like remove, but ALL elements from [first, last]) without resizing the vector? I need to keep it's maximum size that it reached at runtime to prevent reallocs.
Thanks!
vector::erase() erase() function is used to remove elements from a container from the specified position or range.
You need to use std::remove algorithm to move the element to be erased to the end of the vector and then use erase function. Something like: myVector. erase(std::remove(myVector. begin(), myVector.
The idea is to swap the last element and an element you want to remove and then pop_back() . If you need to remove the last elemtent - just pop_back() . The order of the vector will not be the same but you get a fast remove method.
The erase() function can remove an element from the beginning, within, or end of the vector. In order to remove all the elements from the vector, using erase(), the erase() function has to be repeated the number of times there are elements, beginning from the first element.
resize
will never reduce the capacity
of the vector - you can safely use erase
for this.
Use reserve
to make a vector preallocate space for a certain number of items. Unless you actually exceed this limit, no insert
or erase
or resize
will lead to a realloc. If you exceed it, the vector will internally reserve
more space - but it will not reduce the internal capacity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With