set的用法

常用操作:

创建:
set<int> s;
set<int>::iterator it;

插入:
insert()     可以插入单个键值,也可以插入一个容器
例如:s.insert(v.begin(),v.end());

begin()       返回set容器的第一个元素
end()      返回set容器的最后一个元素

大小:
empty()    判断set容器是否为空
max_size()   返回set容器可能包含的元素最大个数
size()      返回当前set容器中的元素个数

rbegin     返回的值和end()相同
rend()     返回的值和rbegin()相同

删除:
clear()           删除set容器中的所有的元素
erase(iterator)    删除定位器iterator指向的值
erase(first,second)删除定位器first和second之间的值
erase(key_value)   删除键值key_value的值

检索:
find()   若找到,返回该键值迭代器的位置,否则,返回最后一个元素后面一个位置。
例如
            set<int> s;
            set<int>::iterator it;
            it=s.find(5);    //查找键值为5的元素
            if(it!=s.end())    //找到
                cout<<*it<<endl;
            else            //未找到
                cout<<"未找到";

lower_bound(key_value)  返回第一个大于等于key_value的定位器
upper_bound(key_value)  返回最后一个大于等于key_value的定位器

自定义比较函数
    (1)元素不是结构体:
        例:
        //自定义比较函数myComp,重载“()”操作符
        struct myComp
        {
            bool operator()(const your_type &a,const your_type &b)
            [
                return a.data-b.data>0;
            }
        }
        set<int,myComp>s;
        ......
        set<int,myComp>::iterator it;
    (2)如果元素是结构体,可以直接将比较函数写在结构体内。
        例:
        struct Info
        {
            string name;
            float score;
            //重载“<”操作符,自定义排序规则
            bool operator < (const Info &a) const
            {
                //按score从大到小排列
                return a.score<score;
            }
        }
        set<Info> s;
        ......
        set<Info>::iterator it; 
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值