JHHK

欢迎来到我的个人网站
行者常至 为者常成

21、set

目录

set

1.构造方法

void set_constructor(){
    //构造方式一:
    set<int> mySet1;
    set<int> mySet1_2 = set<int>();
    
    //构造方式二:
    int a[5] = {1,2,3,4,5};
    set<int > mySet2(a,a+5); //数组a初始化一个set;
     
    //构造方式三:
    set<int> mySet3(mySet2.begin(),mySet2.end());
    
    //构造方式四:
    set<int> mySet4(mySet3); //拷贝构造创建set
}

2.增删改查

void set_zengShanGaiCha(){
    //增
    cout<<"------------增------------"<<endl;
    {
        set<int> mySet;
        mySet.insert(1);
        
        int a[] = {2,3,4};
        mySet.insert(a,a+3);
        
        set<int> mySet2{5,6,7};
        mySet.insert(mySet2.begin(),mySet2.end());
        
        //遍历集合
        for (auto it = mySet.begin(); it!=mySet.end(); it++) {
            cout<<"*it = "<<*it<<endl;
        }
    }
    
    //删
    cout<<"------------删------------"<<endl;
    {
        set<int> mySet{1,2,3,4,5};
        
        mySet.erase(5);
        
        mySet.erase(--mySet.end());
        
        mySet.erase(++mySet.begin(),--mySet.end());
        
        mySet.clear();
        
        //遍历集合
        for (auto it = mySet.begin(); it!=mySet.end(); it++) {
            cout<<"*it = "<<*it<<endl;
        }
    }
    
    //查
    cout<<"------------查------------"<<endl;
    {
        set<int> mySet{1,2,3,4,5};
        //查找一个元素,如果容器中不存在该元素,返回值等于s.end()
        
        auto it = mySet.find(2);
        cout<<"*it = "<<*it<<endl;
        if (it != mySet.end()){
            cout<<"找到了"<<endl;
        }else{
            cout<<"没有找到"<<endl;
        }
        
        
        if (mySet.count(2)) {
            cout<<"mySet.count(2) = "<<mySet.count(2)<<endl;
        }else{
            cout<<"个数为0"<<endl;
        }
    }
    
    
    //size
    cout<<"------------查------------"<<endl;
    {
        set<int> mySet{1,2,3,4,5};
        cout<<"empty = "<<mySet.empty()<<endl;
        cout<<"size = "<<mySet.size()<<endl;
    }
}

3.遍历

void set_enum(){
    //set默认是升序排列的
    set<int> mySet{1,2,3,5,4};
    for (auto it = mySet.begin(); it!=mySet.end(); it++) {
        cout<<"*it = "<<*it<<endl;
    }
}

4.自定义比较器

struct cmp{
    bool operator () (const int &a, const int &b){
        return a < b;
    }
};

void set_cmptest(){
    set<int,cmp> mySet{1,2,3,5,4};
    for (auto it = mySet.begin(); it!=mySet.end(); it++) {
        cout<<"*it = "<<*it<<endl;
    }
}

行者常至,为者常成!





R
Valine - A simple comment system based on Leancloud.