set属于STL里的关联式容器,满足集合的互异性,会自动排序,默认从小到大,

如果set的元素是结构体,排序,需对()重载

 

#include<iostream>
#include<set>
#include<algorithm>
#include<string>
using namespace std;
int main()
{
    set<int,greater<int> > a,b; //默认从小到大,加一个greater<int>就成了从大到小排序,这点和优先队列不一样 
    int i,j,k,t,n,m;
    //
    
    cin>>n;
    for(i=0;i<n;i++)
    {
        cin>>j;
        a.insert(j);
    }
    cout<<"事实证明set会自动排序,默认是从小到大,而且满足互异性"<<endl;
    
    for(set<int>::iterator id=a.begin();id!=a.end();id++)
    cout<<*id<<" ";
    cout<<endl;
    
    cout<<"增:"<<endl;
    a.insert(999);
    a.insert(89);
    for(set<int>::iterator id=a.begin();id!=a.end();id++)
    cout<<*id<<" ";
    cout<<endl;
    
    cout<<"查:"<<endl;
    if(a.count(89)==1)
    cout<<"YES"<<endl;
    else
    cout<<"NO"<<endl;
    if(a.find(999)!=a.end())
    cout<<"YES"<<endl;
    else
    cout<<"NO"<<endl;
    

 

 


    //set的独特之处
    cout<< *(a.lower_bound(15))<<endl; //返回第一个大于15的数的地址 切记,它返回的是迭代器 
    cout<< *(a.upper_bound(25))<<endl;  //返回最后一个大于15的数的地址 
    //对诸如set、map这种关键字唯一的集合而言,lower_bound、upper_bound返回迭代器是相同,关键字val在集合中不存在,二者返回结果一样,
    //对multiset、multimap这类关键字不唯一的集合而言。按照关键字后面一个关键字在集合中出现的次数可分为:关键字val出现在集合中,但是是唯一的,这种情况和set、map情况类似;关键字val出现在集合中,出现多次,这种情况下lower_bound返回第一个出现关键字val对应的迭代器,upper_bound返回位于关键字val对应位置后第一个不是val的位置的迭代器;关键字val不在集合中,这种情况下与set、map一致。
  

 

 

 cout<<"删"<<endl;
    a.erase(a.begin());           
    cout<<*(a.begin())<<endl;
    cout<<a.size()<<endl;
    a.clear();
    cout<<a.size()<<endl;
     
    
    return 0;
}

 

set学习小记

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-22
  • 2021-11-18
  • 2021-07-18
猜你喜欢
  • 2022-12-23
  • 2021-08-14
  • 2021-11-03
  • 2022-01-20
  • 2021-12-28
  • 2022-01-21
  • 2021-12-07
相关资源
相似解决方案