Say I have a std::vector with 5 elements and I need to delete elements from indexes 1 and 3 what would be the fastest way to do this. Are there any helper methods in the standard library that could do this for me ?
We shall have to perform some remove operation using erase() function of vector class type to remove using indices, and finally display rest of elements. The erase function does not take the index directly. We shall have to pass its address by passing v. begin()+index, here v is the vector and v.
All the elements of the vector are removed using clear() function. erase() function, on the other hand, is used to remove specific elements from the container or a range of elements from the container, thus reducing its size by the number of elements removed.
You could use the erase
function. For this specific case you mention something like this:
myvector.erase (myvector.begin()+3);
myvector.erase (myvector.begin()+1);
will do the trick. You have to provide an iterator to the erase
function and I suggest you read documentation for its use. The above should work for your case. Note that each call to erase will change the index of the remaining elements AFTER the removed position though as the internal array elements will be adjusted relative to the item removed.
In response to your comment, you can only erase one element at a time, UNLESS they are contiguous indices in which case you can use the range based version of erase taking a start and end iterator. For example if you want to erase indices 1,2 AND 3 use
myvector.erase (myvector.begin()+1,myvector.begin()+4);
As I already mentioned the indices of items after the one you erase will downshift accordingly. This is unavoidable though as an array cannot have "gaps" in it.
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