假设有一个容器中存放着 int ,Container<int> c, 现在想从其中删除数值 1963,可以有如下方法:

1: c.erase(remove(c.begin(), c.end(), 1963), c.end()); // c is continguous memory container
2: c.remove(1963); // c is list
3: c.erase(1963) // c is standard associative container

对于 continguous memory container 来说, std::remove() 可以保证返回的 iterator 之前的内存中不包含被删除的值,配合 erase 来用,形成所谓的 erase-remove idiom 。而对于 List 来说,应该调用 list 本身的 remove() 方法。对于 map,set 等等,则必须使用 erase() 方法,而不能使用 remove() ,对 associative container 使用 remove() 可能会覆盖容器存储的内容,甚至破坏容器。

假设我们现在想给定一个条件( bool badValue(int x) )并用这个条件来判断有哪些 Entry 需要删除,对 vector、string、deque、list 可以用下列方法:

1: c.erase(remove_if(c.begin(), c.end(), badValue), c.end()); // for vector, string, deque ...
2: c.remove_if(badValue); // for list.

associative container 没有类似的方法,但可以自行遍历删除:

AssocContainer<int> c;
for (AssocContainer<int>::iterator i=c.begin(); i != c.end(); ++i)
{
if (badValue(*i))
{
c.erase(i); //XXX: This is wrong: when this get executed, iterator will become
//XXX: invalid, and ++i will lead to undefined behaviour.
}
} for (AssocContainer<int>::iterator i=c.begin(); i != c.end(); /*Nothing*/)
{
if (badValue(*i))
{
c.erase(i++); //XXX: This works, because we are passing unincreased value to erase,
//XXX: but we get it increased before it was passed to erase().
}
else
{
i++;
}
}
 

最新文章

  1. 在Linux中查看所有正在运行的进程
  2. WCF启用日志追踪
  3. windows下Gulp安装
  4. 【LeetCode 208】Implement Trie (Prefix Tree)
  5. Android SDK安装时碰到的问题之解决办法
  6. popup
  7. STM32F103 ------ BOOT0 / BOOT1
  8. 概率图模型 基于R语言 这本书中的第一个R语言程序
  9. github更新,发布地址,燃尽图,总结
  10. Java基础-线程安全问题汇总
  11. InfoQ 趋势报告:架构和设计领域技术演变详解
  12. 纯js实现最简单的文件上传(后台使用MultipartFile)
  13. Qt编写密钥生成器+使用demo(开源)
  14. 代码使用了php的包管理器composer,include到你的php脚本
  15. ASP/ASP.NET/VB6文件上传
  16. 基于ARM的射频识别读卡器电路设计
  17. wordpress 主题开发
  18. Web框架Django
  19. Messenger和MVVM中的View Services
  20. filter() 方法创建一个新数组

热门文章

  1. ural 2032 Conspiracy Theory and Rebranding (数学水题)
  2. kubernetes 之ingress
  3. Ansible8:Playbook循环
  4. HAproxy Json日志格式配置
  5. Docker应用三:Dockerfile使用介绍(以安装redis为例)
  6. 转:苹果Xcode帮助文档阅读指南
  7. linux下项目上线配置nginx+tomcat
  8. IE6下面的css调试工具
  9. CSS3 实现的一个简单的&quot;动态主菜单&quot; 示例[转]
  10. Docker 初相见