0

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

2 回答 2

3

正如您所说的向量的大小发生了变化,还要注意索引也会发生变化,因此您不会删除您认为的元素。我可以建议对索引向量 ( std::sort) 进行排序,然后从最大的索引向下删除。这样,先前的索引不会因删除之前的索引而失效。

于 2013-10-18T10:06:33.330 回答
-1

vec.begin() + index_2_b_el[i]是一个迭代器,erase 使所有对被擦除元素的迭代器以及它们之间的元素和容器的末尾都失效。过去的迭代器也无效。

所以第一次擦除后,vec.begin() + index_2_b_el[1]不再vec.begin() + index_2_b_el[2]有效

最好的解决方案是使用Erase-remove_idiom

于 2013-10-18T10:09:12.570 回答