• STL


    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

  • 相关阅读:
    python基础知识0-5(单双向队列)
    python基础知识0-4
    python函数篇0-1
    面试题17:合并两个排序的链表
    面试题16:反转链表
    面试题15:链表中倒数第k个结点
    面试题14:调整数组顺序使奇数位于偶数前面
    面试题13:在O(1)时间删除链表结点
    面试题12:打印1到最大的n位数
    面试题11:数值的整数次方
  • 原文地址:https://www.cnblogs.com/davidgu/p/4775726.html
Copyright © 2020-2023  润新知