简单的答案:
for (list<int>::iterator it = v.begin();it!= v.end();){
if (*it == 3){
it = v.erase(it);
} else {
it++;
}
}
看到了STL容器删除元素的陷阱一文中说对于节点式容器(map list set)和 顺序式容器(vector string deque)需要有不同的删除方式,验证后发现,对于上述的解决方案是适用于所有容器的,而
for (list<int>::iterator it = v.begin();it!= v.end();){
if (*it == 3){
v.erase(it++);
} else {
it++;
}
}
只适用于节点式容器(非连续储存的容器)。
这是因为erase函数删除后都返回下个元素的位置,而不是上文中说的void
An iterator pointing to the new location of the element that followed the last element erased by the function call. This is the container end if the operation erased the last element in the sequence.
from std::vector::erase & std::list::erase
它们的区别在于,顺序式容器(连续储存的容器)的迭代器在使用后就被释放了,而节点式容器的迭代器一直保留。
it=find(vec.begin(),vec.end(),88);
vec.insert(it,2,77); //迭代器标记的位置前,插入数据;
cout<<*it<<endl; //会崩溃,因为迭代器在使用后就释放了,*it的时候就找不到它的地址了;
ref: https://blog.csdn.net/gogokongyin/article/details/51178378