[STL]list的erase正确与错误用法


STL中list的erase用法
erase的作用是,使作为参数的迭代器失效,并返回指向该迭代器下一参数的迭代器。
如下:


  1. list<DotSource> ParticleSystem;
  2. list<DotSource>::iterator pointer;
  3. if(pointer->dead == true)
  4. {
  5.    pointer = ParticleSystem.erase(pointer);
  6. }

有一段关于错误使用erase的程序

  1. #include<stdio.h>
  2. #include<list>
  3. using namespace std;
  4. int main()
  5. {
  6.   std::list<int>test_list;
  7.   std::list<int>::iterator test_list_it;

  8.   test_list.push_back(1);

  9.   test_list_it = test_list.begin();
  10.   for(;test_list_it != test_list.end();test_list_it++)

  11.   {
  12.   test_list.erase(test_list_it);
  13.   }
  14. }

问题:该程序不能跳出循环
原因:test_list.erase(test_list_it);每次做erase时都有可能使迭代器失效,test_list_it++就发生错误了。可以参见effective stl一书。所有容器做erase操作时都有可能使迭代器失效。
 
改为:

  1. for(;test_list_it != test_list.end();)
  2. {
  3.    test_list.erase(test_list_it++);
  4. }
or

  1. for(;test_list_it != test_list.end();)
  2. {
  3.    std::list<int>::iterator iter_e=test_list_it++;
  4.    test_list.erase(iter_e);
  5. }

注意:

  1. for(;test_list_it != test_list.end();test_list_it++;)
  2. {
  3.    std::list<int>::iterator iter_e=test_list_it;
  4.    test_list.erase(iter_e);
  5. }

这样任然是错误的,原因是:iter_e=test_list_it 是指针值的复制,它俩其实指向同一个位置,所以iter_e失效那么test_list_it也会失效,所以test_list_it++就会有问题
如果是:

  1. for(;test_list_it != test_list.end();)
  2. {
  3.    std::list<int>::iterator iter_e=test_list_it++;
  4.    test_list.erase(iter_e);
  5. }

则没有问题。
<script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"16"},"share":{}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script>
阅读(1600) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~
评论热议
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值