STL中不同容器的删除操作

STL中不同容器的删除操作

参考资料:effective STL

说明

/* 说明:
1、对于顺序容器,如vector、deque和string等,删除操作应该用如下形式:
vec.erase(remove(vec.begin(), vec.end(), 5), vec.end());
2、对于list,上述1的方法也可以,但是效率的话,应该使用如下形式:
alist.remove(3);
3、对于关联容器,如set、multiset、map、multimap等,则应该使用如下形式:
aset.erase(5);
*/

测试代码

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <deque>
#include <list>
#include <set>
#include <map>

using namespace std;

/* 说明:
1、对于顺序容器,如vector、deque和string等,删除操作应该用如下形式:
    vec.erase(remove(vec.begin(), vec.end(), 5), vec.end());
2、对于list,上述1的方法也可以,但是效率的话,应该使用如下形式:
    alist.remove(3);
3、对于关联容器,如set、multiset、map、multimap等,则应该使用如下形式:
    aset.erase(5);
*/

int main() {
    //vector
    cout << "about vector: " << endl;
    vector<int> vec = {2, 8, 4, 7, 9, 2};
    vec.erase(remove(vec.begin(), vec.end(), 2), vec.end());

    //string
    cout << "about string: " << endl;
    string str = "asdfjklalsdkfjjklasdf";
    str.erase(remove(str.begin(), str.end(), 'a'), str.end());

    //deque
    cout << "about deque: " << endl;
    deque<int> deq = {3, 8, 5, 2};
    deq.erase(remove(deq.begin(), deq.end(), 3), deq.end());

    //list
    cout << "about list: " << endl;
    list<int> alist = {1, 8, 3, 9, 4};
    /* alist.erase(remove(alist.begin(), alist.end(), 8), alist.end()); */
    alist.remove(8);
    for(auto num : alist) {
        cout << num << endl;
    }

    //multiset
    cout << "about set: " << endl;
    multiset<int> mset = {1, 1, 1, 3, 2, 2, 5};

    mset.erase(1);
    for(auto num : mset) {
        cout << num << endl;
    }

    //map
    cout << "about map: " << endl;
    map<int, string> amap = {
        {1, "abc"},
        {2, "sdf"},
        {3, "343sd"}
    };
    amap.erase(2);

    for(auto i : amap) {
        cout << i.first << ", " <<  i.second << endl;
    }

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值