STL 排序容器multiset和set用法详解

前言:希望在大量数据中进行的元素增加、删除、查找都在log(n)复杂度内完成,排序+二分查找显然不可以,因为新加入数据就要进行重新排序。而使用“平衡二叉树”数据结构存放数据就可以达到目的,在STL中体现为以下四种排序容器:multiset、set、multimap、map。

 multiset:

头文件:#include<set>

用法:multiset<T>st;定义了一个multiset类型变量st,st里面可以存放T类型的数据,并且能自动排序。开始st为空

默认排序规则从小到大。

可用st.insert添加元素,st.find查找元素,st.erase删除元素。

multiset <int> st;

元素添加(注意前后代码连贯):

    int num[6] = {3,5,21,456,7};
	for (int i = 0; i < 5; i++)
	{
		st.insert(num[i]);//插入的是num[i]的复制品
	}

元素遍历:

multiset<int>::iterator i;//迭代器i,近似于指针
	for ( i=st.begin();i!=st.end();++i)
	{
		cout << *i<<" ";
	}

元素查找:

	i = st.find(21);//找到返回指向元素的迭代器
	i = st.find(9);//找不到返回值为st.end()
	if (i==st.end())
	{
		cout << "元素未找到"<<endl;
	}
	i = st.lower_bound(7);//比7小的元素[begin(),it)中最靠后的迭代器(包括元素本身)
	cout << *i << endl;//7
	i = st.upper_bound(7);//比7大的元素[it,end())中最靠前的迭代器(不包括元素本身)
	cout << *i << endl;//21

元素删除:

st.erase(i);//删除i指向的元素 即21

 

自定义排序规则的multiset容器:

#include <set>
#include <iostream>
#include<cstring>
using namespace std;
int main()
{
	struct Student
	{
		char name[20];
		int score;
        int id;
	};
	struct Rule {
		bool operator()(const Student& s1, const Student& s2) {
			if (s1.score!=s2.score)
			{
				return s1.score > s2.score;//按分数从大到小排列
			}
			else
			{
				return strcmp(s1.name,s2.name)<0;//分数相同的情况下,名字字母顺序小的排在前面
			}
		}
	};
    multiset <Student,Rule> st;
	Student students[4] = { {"jack",87,001},{"Tom",77,002},{"Susan",87,003},{"Tony",98,004} };
	for (int i = 0; i < 4; i++)
	{
		st.insert(students[i]);
	}
	multiset<Student,Rule>::iterator i;//迭代器i,近似于指针
	for ( i=st.begin();i!=st.end();++i)
	{
		cout << i->name<<","<<i->score<<","<<i->id<<endl;
	}
	cout << endl;
    system("pause");
}

输出: 

multiset查找元素的规则:找到元素A即A和找到的元素在multiset中的排序不分先后

Student std1={"Tom",77,004};
    multiset<Student,Rule>::iterator p=st.find(std1);
    if (p!=st.end())//找到
    {
        cout<<"find: "<<p->name<<","<<p->score<<","<<p->id<<endl;
        //按照排序规则{"Tom",77,004}和{"Tom",77,002}的排序不分先后,即能找到
    }

输出:(注意前后代码连贯)

set:

set和multiset的区别在于:

1.set中不能有重复元素(重复=>a排在必须b前面和a必须排在b后面都不成立)

2.set可能插入元素不成功

示例:

#include <set>
#include <iostream>
#include<cstring>
using namespace std;
int main()
{
    set<int>st;
    int num[5]={1,4,2,7,9};
    for (int i ; i<5; i++)
    {
        st.insert(num[i]);
    }
    pair<set<int>::iterator,bool>res=st.insert(2);
    if (res.second==false)
    {
        cout<<"insert fail!"<<endl;
    }

    for (set<int>::iterator i=st.begin() ; i !=st.end(); i++)
    {
        cout<<*i<<",";
    }
    cout<<endl;
    system("pause");
    
}

查看下篇文章了解multimap和map的用法

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值