c++ STL set 使用

来源:互联网 发布:java前端要学什么 编辑:程序博客网 时间:2024/06/03 15:12

  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();//清除所有元素}


0 0