您的位置:首页 > 其它

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

2016-01-25 16:41 393 查看
原文:http://blog.sina.com.cn/s/blog_782496390100rtyp.html
STL中list的erase用法erase的作用是,使作为参数的迭代器失效,并返回指向该迭代器下一参数的迭代器。如下:

list<DotSource> ParticleSystem;

list<DotSource>::iterator pointer;

if(pointer->dead == true)

{

   pointer = ParticleSystem.erase(pointer);

}

有一段关于错误使用erase的程序
#include<stdio.h>

#include<list>

using namespace std;

int main()

{

  std::list<int>test_list;

  std::list<int>::iterator test_list_it;

  test_list.push_back(1);

  test_list_it = test_list.begin();

  for(;test_list_it != test_list.end();test_list_it++)

  {

  test_list.erase(test_list_it);

  }

}

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

{

   test_list.erase(test_list_it++);

}
or
for(;test_list_it != test_list.end();)

{

   std::list<int>::iterator iter_e=test_list_it++;

   test_list.erase(iter_e);

}

注意:
for(;test_list_it != test_list.end();test_list_it++;)

{

   std::list<int>::iterator iter_e=test_list_it;

   test_list.erase(iter_e);

}

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

{

   std::list<int>::iterator iter_e=test_list_it++;

   test_list.erase(iter_e);

}

则没有问题。


<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
上一篇:设计思绪

下一篇:C++ 类的静态成员详细讲解[静态成员变量链接错误]

相关热门文章
test123

编写安全代码——小心有符号数...

使用openssl api进行加密解密...

一段自己打印自己的c程序...

sql relay的c++接口

linux dhcp peizhi roc

关于Unix文件的软链接

求教这个命令什么意思,我是新...

sed -e "/grep/d" 是什么意思...

谁能够帮我解决LINUX 2.6 10...

给主人留下些什么吧!~~

评论热议
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: