C++标准模板库(STL)——set集合

STL——set集合

只能通过迭代器访问元素

  • 概念:集合,内部自动有序且不含重复元素的容器

  • 定义:set<typename> name;
    typename可以是任何基本类型,或者STL容器(此使>>之间有空格)

  • 头文件:

#include<set>
using namespace std;  //两个必须都有
  • 二维set数组定义:set<int> a[10]
    从a[0]—a[9],每一行均是int型set集合

  • 元素访问:只能通过迭代器 set<int>::iterator it;

  • set常用函数:
    insert(元素x): 将x插入set容器,并自动递增排序和去重,复杂度O(logN)
    size(): 元素个数,复杂度O(1)

#include<iostream>
#include<set>
using namespace std;

int main(){
    int num;
    set<int> a;           //int型set集合a

    for(int i=1;i<=5;i++){
        cin>>num;
        a.insert(num);    //只能通过insert()方法插入元素
    }

    set<int>::iterator it;     //获得集合迭代器it,理解为指针

    for(it=a.begin();it!=a.end();it++){     //从起始地址至结束,迭代器自增输出元素
        cout<<*it<<" ";                     //注意:不支持*(it+i),不支持it<st.end()
    }

    cout<<endl<<a.size();

    return 0;
}
输入:
3 3 2 2 1
输出:
1 2 3
3

find(元素x): 找到元素x并返回其迭代器,复杂度O(logN)
erase(迭代器): 删除迭代器对应元素,复杂度O(1)
erase(迭代器初位置,迭代器末位置): 删除 [起始,终止) 位置的元素
clear(): 清空所有元素,复杂度O(N)

#include<iostream>
#include<set>
using namespace std;

int main(){
    int num;
    set<int> a;                //int型set集合a
    set<int>::iterator it;     //获得集合迭代器it,理解为指针

    for(int i=1;i<=5;i++){
        cin>>num;
        a.insert(num);    //只能通过insert()方法插入元素
    }

    a.erase(a.find(3));   //找到元素3的迭代器,删除

    a.erase(a.begin(),a.find(2));    //从开头到元素2前一个,全部删除

    for(it=a.begin();it!=a.end();it++){     //从起始地址至结束,迭代器自增输出元素
        cout<<*it<<" ";                     //注意:不支持*(it+i),不支持it<st.end()
    }

    cout<<endl<<a.size();            //长度

    return 0;
}
输入:
4 3 3 2 1
输出:
2 4 
2
  • 常见用途:
  1. 自动去重并按升序排列,遇到不方便开数组时可以考虑使用
  2. set中元素是唯一的,如果需要处理不唯一的情况,可使用multiset; 如果只去重不排序,可使用unordered_set
发布了16 篇原创文章 · 获赞 0 · 访问量 530

猜你喜欢

转载自blog.csdn.net/clfxyz/article/details/105687059