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;
}