STL:STL关联容器 set

STL关联容器set详解与实战
本文介绍了STL关联容器set的特点、操作方法,包括使用迭代器遍历、插入和查找。通过力扣和51nod的编程题目,如存在重复元素、找到消失的数字、寻找重复数和计算交集等,展示了set在解决实际问题中的应用。

STL关联容器 set

集合容器(set):快速查找,不允许重复值

set 的特点:有序且不重复

1. 操作

1.1 使用迭代器遍历

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

int main(){
   
   
        // 迭代器遍历
        set<int> s = {
   
   1,5,3,7,3};
        for(auto it = s.begin();it != s.end();++it){
   
   
                cout << *it << " ";
        }
        cout << endl;

        for(auto n:s){
   
   
                cout << n << " ";
        }
        cout << endl;
}

结果为:

1 3 5 7 
1 3 5 7

1.2 插入

将某一个数值插入到数组中

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

int main(){
   
   
        set<int> s = {
   
   1,5,3,7,3};

        for(auto n:s){
   
   
                cout << n << " ";
        }
        cout << endl;

        // 添加数据
        // pair<set<int>::iterator,bool> res = s.insert(10);
        auto res = s.insert(10);          // 插入数字10
        if(res.second){
   
                 // 插入成功即插入不重复,res.second为true
                cout << *(res.first) << "插入成功" << endl;    // *(res.first)是具体数值
        }else{
   
                          // 插入失败即插入数值重复
                cout << "插入失败" << endl;
        }

        for(auto n:s){
   
   
                cout << n << " ";
        }
        cout << endl
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值