STL封装之multiset 超全整理

multiset内部的原理是用平衡二叉树实现,因此无论是查找还是删除操作,时间复杂度都比较低,给我们很大的遍历。
头文件:set

#include <set>

容器命名:multiset<数据类型>容器名称

操作集:
1.插入,删除

	multiset<int> ms;
    ms.insert(7);//插入元素7
    ms.insert(10);
    ms.insert(5);
    cout << "ms contains:";
    while (!ms.empty())//empty判断容器ms是不是为空
    {
        cout << ' ' << *ms.begin();
        ms.erase(ms.begin());//删除容器首位置的元素,即(容器中最小的元素)
    }//ms contains: 5 7 10
	
	ms.erase(first, last);//删除容器中在区间[first, last)中的元素
    ms.erase(pos);//删除容器中第pos个元素
	

2.查找

	ms.find();//在容器中找到某一个值,找到了返回地址,找不到,返回容器末位置  
	
	for (int i=1; i<= 5; i++)
        ms.insert(i * 10);   // 10 20 30 40 50
    it=ms.find(50);//找到的是元素地址
    cout<<"The value of position it is:"<<*it<<endl;//The value of position it is:50
    ms.erase (it);//删除位置为it的元素
    ms.erase (ms.find(40));
    cout << "ms contains:";
    for (it = ms.begin(); it != ms.end(); it++)
        cout << ' ' << *it;//ms contains: 10 20 30

3.判断容器是都为空,容器大小,起始终止位置

	ms.empty();//容器为空,返回true,否则返回false
	ms.size();//返回容器大小
	ms.clear();//清除容器
	ms.begin();//返回容器的起始位置
    ms.end();//返回容器的结束位置

4.计算某一个元素出现的次数

	int myints[]= {73,12,22,73,73,12};//数某一个数出现的次数
    multiset<int> ms (myints,myints + 6);
    cout << "73 appears " << ms.count(73) << " times in ms.\n";//73 appears 3 times in ms.
    cout << "12 appears " << ms.count(12) << " times in ms.\n";//12 appears 2 times in ms.

5.输出容器中的所有元素

    for (multiset<int>::iterator it = ms.begin(); it != ms.end(); it++)
        cout <<*it<<" ";

6.swap函数

	
int myints3[]= {1,2,3,4,5,6};
    multiset<int> first(myints3, myints3 + 3);     // 4,19,72
    multiset<int> second(myints3 + 3, myints3 + 6);  // 20,20,36
    first.swap(second);
    cout << "first contains:";
    for (multiset<int>::iterator it = first.begin(); it != first.end(); it++)
        cout << *it<<" ";
    cout << "\nsecond contains:";
    for (multiset<int>::iterator it = second.begin(); it != second.end(); it++)
        cout << *it<<" ";
        //first contains:4 5 6
		//second contains:1 2 3
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值