如何优雅的在遍历C++容器的时候删除元素

简单的答案:

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

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值