STL - 移除(remove)和释放(erase)集合元素

remove(移除):

这个操作并不是真正地删除元素,它会移除指定的元素,然后后面的元素依次前移,最后用别的元素来补充。

erase(释放):

这个操作会指定释放区间的头和尾迭代器(iterator)。

 

如果要一次性删除指定元素:

coll.erase(remove(coll.begin(), coll.end(), [removed element]), coll.end()); 

 

代码如下:

 

list<int> coll1;

    for (int i = 1; i <= 6; ++i)
    {
        coll1.push_front(i);
        coll1.push_back(i);
    }

    cout << "** collection 1: **" << endl;
    ContainerUtil<list<int>>::printElements(coll1);

    // remove all elements with value 3
    list<int>::iterator end = remove(coll1.begin(), coll1.end(), 3);

    cout << "** collection 1(after remove elements 3): **" << endl;
    ContainerUtil<list<int>>::printElements(coll1);

    // print number of removed elements
    cout << "number of removed elements : " << distance(end, coll1.end()) << endl;

    // release 'removed' elements
    coll1.erase(end, coll1.end());
    cout << "** collection 1(after releasing removed elements): **" << endl;
    ContainerUtil<list<int>>::printElements(coll1);

    // remove & release elements with value 4 all at once
    coll1.erase(remove(coll1.begin(), coll1.end(), 4), coll1.end());
    cout << "** collection 1(after remove & release elements 4): **" << endl;
    ContainerUtil<list<int>>::printElements(coll1);

 

运行结果:

** collection 1: **
  6  5  4  3  2  1  1  2  3  4  5  6
** collection 1(after remove elements 3): **
  6  5  4  2  1  1  2  4  5  6  5  6
number of removed elements : 2
** collection 1(after releasing removed elements): **
  6  5  4  2  1  1  2  4  5  6
** collection 1(after remove & release elements 4): **
  6  5  2  1  1  2  5  6

 

转载于:https://www.cnblogs.com/davidgu/p/4775726.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值