multiset用法

  c++语言中,multiset是<set>库中一个非常有用的类型,它可以看成一个序列,插入一个数,删除一个数都能够在O(logn)的时间内完成,而且他能时刻保证序列中的数是有序的,而且序列中可以存在重复的数。

 

简单的运用:

int main()
{
    //freopen("../in.txt","r",stdin);
    int x;
    scanf("%d",&x);
    multiset<int> h;
    while (x!=0) // 插入数
    {
        h.insert(x);
        scanf("%d",&x);
    }
    while (!h.empty())
    {
        auto c = h.begin();  // 按升序输出
        printf("%d\n",*c);
        h.erase(c);
    }
    return 0;
}

 

放入自定义的数据类型

 

struct new_type{
    int x;
    int y;
};
multiset<new_type> h;

但是这种写法的multiset其实是没有意义的,因为它不知道根据什么样的一个顺序进行排列

 

我们可以定义一个比较类cmp,cmp内部的operator函数的作用是比较new_type类型a和b的大小(以x为第一关键字,y为第二关键字):

struct new_type{
    int x;
    int y;
};

struct cmp{
    bool operator()(const new_type&a,const new_type&b)
    {
        if (a.x != b.x)
            return a.x<b.x;
        else
            return a.y<b.y;
    }
};
multiset<new_type,cmp> h;

 

multiset的函数

因为是<set>的一部分,所以multiset的大多数操作函数都和set一样

这里只将几个比较容易弄错的

 

 

posted @ 2019-07-30 10:57  _Ackerman  阅读(538)  评论(0编辑  收藏  举报