To remove a value from a vector we must follow the erase-remove idiom, the first step is to find the value that we wish to remove and move it to the front of the container. This is performed using remove which returns an iterator pointing to the new end of the vector, effectively ignoring the removed values. For example:
Will print this to screen:
If we want to remove all 5
values from myVec
we can do this:
Which will produce the following data on the screen:
Will print this to screen:
However, the vector’s size has not changed. The removed values are now at the end of the vector
and could still be accessed by using myVec.end()
instead of NewEnd
. So now we will
remove the values using erase,
to complete the process. If erase
is passed 2 iterators it will erase all of the values between
those 2 points. So we want to erase every value between NewEnd
and myVec.end()
:
We can test that this has worked by attempting to write the whole vector to screen:
Which gives us a vector completely free of our erased data:
It is also possible to combine this idiom into a one liner:
It should be noted that this code will modify vectors in place so should be used with caution.