How to remove elements from container is a common C++ interview question, so you can earn some brownie points if you read this page carefully.

如何从容器中删除元素是C ++常见的面试问题,因此,如果仔细阅读此页,可以赚取布朗尼积分。

The erase–remove idiom is a C++ technique to eliminate elements that fulfill a certain criterion from a container. However, it is possible to eliminate elements with traditional hand-written loop, but the erase–remove idiom has several advantages.

删除删除惯用语是一种C ++技术,用于从容器中删除满足特定条件的元素。 但是,可以使用传统的手写循环来消除元素,但是“擦除-删除”这一惯用法具有多个优点。

比较方式 (Comparison)

// Using a hand-written loop
std::vector<int> v = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (auto iter = v.cbegin(); iter < v.cend(); /*iter++*/)
{if (is_odd(*iter)){iter = v.erase(iter);}else{++iter;}
}// Using the erase–remove idiom
std::vector<int> v = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
v.erase(std::remove_if(v.begin(), v.end(), is_odd), v.end());

As you can see, the code with hand-written loop requires a bit more typing, but it also has a performance issue. Each erase call has to move forward all the elements after the deleted one, to avoid “gaps” in the collection. Calling erase multiple times on the same container generates lots of overhead of moving the elements.

如您所见,带有手写循环的代码需要更多的输入,但同时也存在性能问题。 每个erase调用都必须将所有元素移到已删除元素之后,以免集合中出现“空白”。 在同一容器上多次调用erase产生大量移动元素的开销。

On the other hand, the code with the erase–remove idiom is not only more expressive, but it also is more efficient. First, you use remove_if/remove to move all elements which don’t fit the remove criteria to the front of the range, keeping the relative order of the elements. So after calling remove_if/remove, a single call of erase deletes all remaining elements at the end of the range.

另一方面,带有“擦除-删除”惯用语的代码不仅更具表现力,而且效率更高。 首先,使用remove_if/remove将所有不符合删除条件的元素移动到范围的前面,并保持元素的相对顺序。 因此,在调用remove_if/remove ,一次erase删除范围末尾的所有剩余元素。

(Example)

#include <vector> // the general-purpose vector container
#include <iostream> // cout
#include <algorithm> // remove and remove_ifbool is_odd(int i)
{return (i % 2) != 0;
}void print(const std::vector<int> &vec)
{for (const auto& i : vec)std::cout << i << ' ';std::cout << std::endl;
}int main()
{// initializes a vector that holds the numbers from 1-10.std::vector<int> v = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };print(v);// removes all elements with the value 5v.erase(std::remove(v.begin(), v.end(), 5), v.end());print(v);// removes all odd numbersv.erase(std::remove_if(v.begin(), v.end(), is_odd), v.end());print(v);// removes multiples of 4 using lambdav.erase(std::remove_if(v.begin(), v.end(), [](int n) { return (n % 4) == 0; }), v.end());print(v);return 0;
}/*
Output:
1 2 3 4 5 6 7 8 9 10
1 2 3 4 6 7 8 9 10
2 4 6 8 10
2 6 10
*/

资料来源 (Sources)

“Erase–remove idiom” Wikipedia: The Free Encyclopedia. Wikimedia Foundation, Inc. en.wikipedia.org/wiki/Erase-remove_idiom

“删除擦除成语”维基百科:免费百科全书。 Wikimedia Foundation,Inc. zh.wikipedia.org/wiki/Erase-remove_idiom

Meyers, Scott (2001). Effective STL: 50 Specific Ways to Improve Your Use of the Standard Template Library. Addison-Wesley.

迈耶斯·斯科特(2001)。 有效的STL:50种提高标准模板库使用率的特定方法。 艾迪生-韦斯利。

翻译自: https://www.freecodecamp.org/news/how-to-remove-elements-from-a-container-in-c/

如何在C ++中从容器中删除元素相关推荐

  1. MFC中STL容器中Vector,List,Map基本用法汇总

    容器就是数据结构的泛指,迭代器就是指针的泛指,可以指向元素.它可以用来存储数据,就比如杯子用来装水一样.而STL中的容器有很多,它包括vector,list,map,deque,set等.我就简单列举 ...

  2. STL中map/vector的删除元素操作

    在我们使用C++中的STL的时候,可以使用迭代器iterator进行遍历,但是当我们通过iterator对vector和map删除元素的时候,要格外的小心,往往操作不当,导致iterator失效,后果 ...

  3. 集合中的遍历以及删除元素

    package collection;import java.util.ArrayList; import java.util.Collection; import java.util.Iterato ...

  4. qt中QList使用removeAt()删除元素

    提要 QList删除元素的时候需要特别注意一点,将元素删除后链表中元素的排列.删除一个元素后,后面的元素会补到被删元素的位置,这样在for循环中若删除元素后继续执行下标++,则会少遍历元素.下面看一个 ...

  5. JS中字符串和数组删除元素方法

    1.字符串删除元素方法 按下标删除 可以使用提供的库函数slice(). substring() .substr() 进行截取,实质是提取然后赋给原字符串str 按值删除 主要用replace()替换 ...

  6. python list删除元素_python中List添加、删除元素的几种方法

    原博文 2015-06-21 18:51 − 一.python中List添加元素的几种方法 List 是 Python 中常用的数据类型,它一个有序集合,即其中的元素始终保持着初始时的定义的顺序(除非 ...

  7. js中数组插入、删除元素操作

    /** 删除数组元素:Array.removeArr(index)*/Array.prototype.removeArr = function (index) {if (isNaN(index) || ...

  8. c++容器vector删除元素erase()与迭代器的使用

    写代码时用 for 循环删除 vector 中的元素发现总是报错,后来最细看了下 erase() 方法发现 erase()方法使用后原来的迭代器失效,返回新的迭代器. 正确的使用方法是: #inclu ...

  9. docker 查看已安装容器_docker中的容器安装PHP扩展件

    案例:memcached是一个php的缓存扩展,通过它把数据库的查询结果缓存在内存中,而内存的读写速度比SSD还要快几十倍,解决了硬盘缓存速度的瓶颈,加快服务器网页加载速度.流程: 一.前期构建PHP ...

最新文章

  1. 微服务应该这么搞,万字长文谈微服务经历!
  2. JS判断数组里面是否包含指定的数
  3. 要买东西,要买好的,提高效率,经常用的
  4. java图片上传(mvc)
  5. Vue.js之初印象
  6. 微信支付将推双面屏;库克谈收购英特尔基带业务;Chrome 76 稳定版发布 | 极客头条...
  7. Hive thrift服务(将Hive作为一个服务器,其他机器可以作为客户端进行访问)
  8. textarea 滚动条属性设置
  9. 超出ipc连接数范围_终端服务器超出了最大允许连接数的解决办法 (全文)
  10. §6.5 分离性公理与子空间,(有限)积空间和商空间
  11. 微信小程序 自定义标题栏
  12. 阿里设计师:B端产品国际版体验设计
  13. ImprovedGAN论文略读
  14. 下载正版的Windows操作系统和office软件
  15. Linux两台主机之间建立信任关系
  16. FPGA图像工程师的六脉神剑——“选扫掌仿习练”
  17. 计算机网络微课堂CSMA/CD协议-争用期碰撞时刻以及收到碰撞信号的时间时间的推导
  18. 穿过任意防火墙NAT的远程控制软件TeamViewer
  19. 如何隐藏计算机桌面窗口,电脑桌面窗口被隐藏,如何取消隐藏? 打开网页,各种软件,桌面下边的窗口都被隐藏了,很不方便。...
  20. Delphi2009 反射机制的使用

热门文章

  1. 【转】判断UIViewController是否正在显示
  2. RecycleView的notifyItemRemoved使用注意
  3. 从入门到放弃的javaScrip——队列
  4. 新闻网站个人中心(查询用户的关注信息)流程分析
  5. Angular开山篇
  6. 菜鸟物流云是如何帮助快递合作伙伴解决双11巨大业务负荷的?
  7. [Python] 中文路径和中文文本文件乱码问题
  8. Mybatis调用Oracle的存储过程
  9. 【124】排球基本技术
  10. JQuery模板插件jquery.tmpl-动态ajax扩展