c++ STL set 使用

  set 集合容器

    实现了红黑树的平衡二叉检索树的数据结构,插入元素时,它会自动调整二叉树的排列,把元素放到适当的位置,以保证每个子树根节点键值大于左子树所有节点的键值,小于右子树所有节点的键值;另外,还得保证根节点左子树的高度与右子树高度相等。

   平衡二叉检索树使用中序遍历算法,检索效率高于vector、deque和list等容器,另外使用中序遍历可将键值按照从小到大遍历出来。

   构造set集合主要目的是为了快速检索,不可直接去修改键值


#include<iostream>
#include<set>
using namespace std;
//自定义比较函数
struct cmp
{
    bool operator()(const int &a,const int &b)const{
        return a>b;
    }
};
struct node
{
    int num;
    //如果是结构体,可自行给定比较函数
    bool operator<(const node &other)const{
        return num<other.num;
    }
    node(int _num):num(_num){}
};
typedef set<node>::iterator It1;//迭代器类型
typedef set<int,cmp>::reverse_iterator It2;//反向迭代器类型
int main()
{
    set<node>st1;
    set<int,cmp>st2;

    //插入
    for(int i=0;i<5;i++){
        st1.insert(node(i));
        st2.insert(i);
    }

    //遍历,已排序
    for(It1 it=st1.begin();it!=st1.end();it++)
        cout<<it->num<<endl;

    //反向遍历,已排序
    for(It2 it=st2.rbegin();it!=st2.rend();it++)
        cout<<*it<<endl;

    node x=node(1);
    //元素删除
    st1.erase(x);

    //元素查找
    It1 it=st1.find(x);
    if(it!=st1.end())
        cout<<"Yes"<<endl;
    else cout<<"No"<<endl;

    cout<<"size="<<st1.size()<<endl;//大小
    cout<<"empty="<<st1.empty()<<endl;//为空

    st1.clear();
    st2.clear();//清除所有元素
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值