Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete from specific indexes in a std::vector [duplicate]

Tags:

c++

vector

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 ?

like image 201
MistyD Avatar asked Dec 14 '13 11:12

MistyD


People also ask

How do I remove a specific index from a vector in C++?

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.

How do I remove a specific index from a vector?

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.


1 Answers

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.

like image 175
mathematician1975 Avatar answered Nov 15 '22 05:11

mathematician1975