multiset和set的简单用法

                multiset<T>  st;

1、定义一个multiset变量st,st里面可以存放T类型的数据,并且能自动排序,自动把st里面的变量由小变大排序,开始st为空;

2、排序规则:表达式 “a<b"为true,则a排在b前面;

3、可用 st.inser 添加元素,st.find查找元素,st.erase删除元素,复杂度都是log(n)。

样例:

#include<iostream>
#include<cstring>
#include<set>//使用multiset和set头文件
using namespace std;
int main()
    {
        multiset<int> st;
        int a[10]={1,14,12,13,7,13,21,19,8,8};
        for(int i = 0;i < 10 ;i++)
                st.insert(a[i]);//插入的是a[i]的复制品
        multiset<int>::iterator i;//迭代器,近似于指针
        for(i = st.begin(); i != st.end(); i++)
            cout<< * i <<",";
        cout<<endl;//输出1,7,8,8,12,13,13,14,19,21,
        i = st.find(22); //查找22,返回值是迭代器
        if( i == st.end()) //找不到则返回值为 end()
            cout << "not found" << endl;
        st.insert(22);//插入22
        i = st.find(22);
        if( i == st.end())
            cout << "not found" << endl;
        else
            cout<< "found:" << *i <<endl;
        //找到则返回指向找到的元素迭代器
        //输出 not found;
        //     found:22
        i = st.lower_bound(13);//返回大于等13,离13最近的元素
        cout<< *i << endl;//输出13
        i = st.upper_bound(8);//返回大于8,离8最近的元素;
        cout<< *i <<endl;//输出12
        st.erase(i);//删除迭代器i指向的元素,即12
        for(i = st.begin(); i != st.end() ; i++)
            cout << *i << ",";//输出1,7,8,8,13,13,14,19,21,22,
        return 0;
    }

迭代器:

multiset<T>::iterator p;

p是迭代器,相当于指针,可用于指向multiset中的元素。访问multiset中的元素要通过迭代器。

与指针的不同: multiset上的迭代器可 ++ ,--, 用 != 和 == 比较,不可比大小,不可加减整数,不可相减

multiset st;

st.begin() 返回值类型为 multiset::iterator, 是指向st中的头一个元素的迭代器

st.end() 返回值类型为 multiset::iterator, 是指向st中的最后一个元素后面的迭代器

对迭代器 ++ ,其就指向容器中下一个元素,-- 则令其指向上一个元素

自定义排序规则的multiset

multiset<T,规则名称>  st;

struct Rule1 { bool operator()( const int & a,const int & b) const

{ return (a%10) < (b%10); }

//返回值为true则说明a必须排在b前面 };

multiset<T,Rule1>  st;

st中的排序规则就会按照rule1进行排序

set的用法

set和multiset的区别在于容器里不能有重复元素 a和b重复

 “a必须排在b前面” 和“b必须排在a前面”都不成立

set插入元素可能不成功

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值