STL set的基本操作

要使用set就要使用#include <set>头文件

set就是一个集合,他会自动去重,自动排序

定义set

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

int main()
{
    set</*类型,比如int,结构体也可以*/typename> /*文件名*/st;

    return 0;
}

插入

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

int main()
{
    st.insert(x);
    //x为st 的类型
    return 0;
}

迭代器

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

int main()
{
    set<typename>::iterator it;

    return 0;
}

迭代器可以用来访问set

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

int main()
{
    set<typename>::iterator it;
    cout << *it << endl;
    //*it就是set里面的元素
    return 0;
}

删除set中的元素

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

int main()
{
    set<typename>::iterator it;
    st.erase(it);//it为迭代器,st.erase(it)是代表删除it位置的元素
    st.erase(x);//x为具体元素,st.erase(x)表示删除x元素
    st.erase(it1,it2);//it1,it2皆为迭代器,表示删除[it1,it2)区间的元素,注意是左闭右开
    return 0;
}

清空set

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

int main()
{
    st.clear();//注意不要传入任何参数,如果传入的话,会报错
    //[Error] no matching function for call to 'std::set<int>::clear(int)
    return 0;
}

第一个位置以及最后一个位置

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

int main()
{
    it1 = st.begin();
    it2 = st.end();//注意st.end()是最后一个位置+1
    return 0;
}

 访问set

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

int main()
{
    set<typename>::iterator it;
    for (it = st.begin();it != st.end();it++)
    {
        //注意判断条件不是  it < st.end();
        //而是   it != st.end();
    }
    return 0;
}

lower_bound以及upper_bound

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

int main()
{
    it = st.lower_bound(x);//在st里找到第一个大于等于x的位置,返回迭代器
    it = st.upper_bound(x);//在st里找到第一个严格大于x的位置,返回迭代器
    //如果用set自带的lower_bound或upper_bound,时间复杂度是O(logn)
    //但使用algorithm里的lower_bound或upper_bound,时间复杂度是O(n)
    return 0;
}

multiset是多重集合,一个数可以出现多遍,但使用erase时,会有一些变化

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

int main()
{
    multiset<typename> st;
    st.erase(x);//x为具体元素,如果有多个x,会把所有的x都删除
    //但如果是迭代器,只会删除it位置的元素
    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值