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.
Yes, size is decreased as you erase elements. Returns the number of elements in the vector.
Erasing an element in a vector is O(n) as we have to remove the element and still need to shift all successive elements to fill the gap created. If a vector has n elements, then in the worst case we will need to shift n-1 elemets, hence the complexity is O(n).
Yes it does. What would the alternative be?
I need to remove elements from the middle of a std::vector.
So I tried:
struct IsEven {
bool operator()(int ele)
{
return ele % 2 == 0;
}
};
int elements[] = {1, 2, 3, 4, 5, 6};
std::vector<int> ints(elements, elements+6);
std::vector<int>::iterator it = std::remove_if(ints.begin() + 2, ints.begin() + 4, IsEven());
ints.erase(it, ints.end());
After this I would expect that the ints
vector have: [1, 2, 3, 5, 6].
In the debugger of Visual studio 2008, after the std::remove_if
line, the elements of ints
are modified, I'm guessing I'm into some sort of undefined behaviour here.
So, how do I remove elements from a Range of a vector?
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