set集合容器

set集合容器实现了红黑树的平衡二叉树的数据结构

#include<set>
#include<iostream>
#include<cstdio>

using namespace std;

///自定义比较函数myComp,重载“()”操作符
struct myComp{
    bool operator()(const int &a,const int &b){
    if(a != b)
        return a > b;
    else
        return a > b;
    }
};

///如果元素是结构体,可以把比较函数写在结构体内
struct Info{
    string name;
    float score;
    ///重载“<”操作符,自定义排序规则
    bool operator < (const Info &a) const{
        ///按score从大到小排列,使用“>”号即可
        return a.score < score;
    }
};

int main(){
    ///定义元素类型为int的对象s,当前没有任何元素
    ///元素的排列采用默认的比较规则,也可以自定义比较规则函数
    set<int> s;

    ///元素的插入与中序遍历
    ///插入了五个元素,第二个8重复,没有插入进去
    s.insert(8);
    s.insert(1);
    s.insert(12);
    s.insert(6);
    s.insert(8);
    ///中序遍历集合中的元素
    set<int>::iterator it;
    for(it = s.begin();it != s.end();it++){
        cout << *it << " ";
    }
    printf("\n");

    ///元素的反向遍历
    set<int>::reverse_iterator rit;
    for(rit = s.rbegin();rit != s.rend();rit++){
        cout << *rit << " ";
    }
    printf("\n");

    ///元素的删除
    s.erase(6);
    for(auto it = s.begin();it != s.end();it++){
        cout << *it << " ";
    }
    printf("\n");

    ///元素的检索
    s.insert(6);
    ///查找键值为6的元素
    it = s.find(6);
    if(it != s.end())
        cout << "找到该元素" << endl;
    else
        cout << "该元素不存在" << endl;
    ///查找键值为20的元素
    it = s.find(20);
    if(it != s.end())
        cout << "找到该元素" << endl;
    else
        cout << "该元素不存在" << endl;

    ///自定义比较函数
    set<int,myComp> ss;
    ss.insert(8);
    ss.insert(1);
    ss.insert(12);
    ss.insert(6);
    ///迭代器
    for(auto it = ss.begin();it != ss.end();it++)
        cout << *it << " ";
    printf("\n");

    set<Info> sss;
    Info info;
    info.name = "Jack";
    info.score = 80.5;
    sss.insert(info);
    info.name = "Tom";
    info.score = 20.5;
    sss.insert(info);
    info.name = "Nacy";
    info.score = 60.5;
    sss.insert(info);
    for(auto it = sss.begin();it != sss.end();it++)
        cout << (*it).name << ":" << (*it).score << endl;
    printf("\n");

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值