Let's say I have a std::vector
of integers:
std::vector<int> v;
v
contains 100 elements, and I want to remove the last 10 elements. I can think of this solution:
v.erase(v.end() - 10, v.end());
Anything better?
If you need to remove multiple elements from the vector, the std::remove will copy each, not removed element only once to its final location, while the vector::erase approach would move all of the elements from the position to the end multiple times.
The standard solution to remove an element from a vector is with the std::vector::erase function. It takes an iterator to the position where the element needs to be deleted. To delete an element at the end of a vector, pass an iterator pointing to the last element in the vector.
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.
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.
You may try this:
v.resize(v.size()-10);
However, you need to benchmark it against your method. I am not sure it is better or even it may be exactly the same.
You may also check the size before resizing:
if(v.size()>=10){
v.resize(v.size()-10);
}
EDIT:
Resize removes elements at the end of the vectors: http://www.cplusplus.com/reference/vector/vector/resize/
If n is smaller than the current container size, the content is reduced to its first n elements, removing those beyond (and destroying them).
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