Question: I'm trying to delete some elements in my vector, which are specified by another index vector. I get a segmentation fault. The reason why I get a segmentation fault is that the size of my vector decrease as the elements get deleted, so it seem like I'm trying to exceed the index. Can anyone help? Thanks in advance

```
#include <iostream>
#include <vector>
using namespace std;

int main()
{   
int a = 5, b = 10 , c = 20, d = 30, e = 40 , f = 50;
vector<int> vec;

vec.push_back(a);
vec.push_back(b);
vec.push_back(c);
vec.push_back(d);
vec.push_back(e);
vec.push_back(f);

vector<int> index_2_b_el;

index_2_b_el.push_back(1); //delete b
index_2_b_el.push_back(3); //delete d
index_2_b_el.push_back(4); //delete e

for(int i=0; i<index_2_b_el.size(); i++)
{
    vec.erase(vec.begin() + index_2_b_el[i]);
    // "b", "d" and "e" should be deleted
}   

for(int i=0; i<vec.size(); i++)
{
    cout<< "vec: "<< vec[i]<<endl;
    // "a", "c" and "f" should remain
}

return 0;
}

```

Answer: 
As you say the size of the vector changes, also note the indices change too so you're not removing the elements you think you are. May I suggest sorting the index vector (`std::sort`), and then removing from the largest index down. That way the previous indices are not invalidated by the removal of the ones before.
`vec.begin() + index_2_b_el[i]` is an interator and erase invalidate all iterators to the erased elements and to the elements between them and the end of the container are invalidated. The past-the-end iterator is also invalidated. 

So after the first erase, `vec.begin() + index_2_b_el[1]` and `vec.begin() + index_2_b_el[2]` are no longer valid

The best solution is to use [Erase-remove\_idiom](http://en.wikipedia.org/wiki/Erase-remove_idiom)