STL集合2

大家好,我是#Y清墨,我曾经讲过集合。今天,我们来讲些例题。

集合交集

交集,是个高中生都不觉得陌生,只用1个符号就能搞定(∩)。

但是,c++编程题可不一样。

不知道的可以看一下定义:

集合论中,设A,B是两个集合,由所有属于集合A且属于集合B的元素所组成的集合,叫做集合A与集合B的交集(intersection),记作A∩B。

这个时候我们就需要召唤劳搭,呸呸,需要用我们前几节课前教的知识集合,不会的小卡拉米可以看下面的链接。

https://blog.youkuaiyun.com/dazys/article/details/142109776?spm=1001.2014.3001.5502icon-default.png?t=O83Ahttps://blog.youkuaiyun.com/dazys/article/details/142109776?spm=1001.2014.3001.5502话不多说,直接开始。

#include<bits/stdc++.h>
using namespace std;
set<int>a,b;
int m,n,t;
int main(){
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        cin>>t;
        a.insert(t);
    }
    cin>>m;
    for(int i=1;i<=m;i++)
    {
        cin>>t;
        b.insert(t);
    }
    set<int>::iterator it;
    for(it=a.begin();it!=a.end();it++)
    {
        if(b.find(*it)!=b.end())cout<<*it<<" ";
        //如果b存在a的元素,则输出当前元素
    }
    return 0;
}

 集合并集

并集,是个高中生都不觉得陌生,只用1个符号就能搞定(∪)。

不知道的可以看一下定义:

给定两个集合A,B,把他们所有的元素合并在一起组成的集合,叫做集合A与集合B的并集,记作A∪B。

但是,c++编程题可不一样。

这个时候我们就需要再次召唤劳搭,呸呸,需要用我们前几节课前教的知识集合,话不多说,直接开始。

#include<bits/stdc++.h>
using namespace std;
set<int>a;
//集合有个特点:自动排序且不会有重复元素
//所以就可以只用一个集合
int m,n,t;
int main(){
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        cin>>t;
        a.insert(t);
    }
    cin>>m;
    for(int i=1;i<=m;i++)
    {
        cin>>t;
        a.insert(t);
    }
    set<int>::iterator it;
    for(it=a.begin();it!=a.end();it++)
    {
        cout<<*it<<" ";
    }
    return 0;
}

### C++ STL `set` 容器概述 `set` 是 C++ 标准模板库(STL)中的关联容器之一,用于存储唯一的键并自动保持有序状态。该容器不允许重复元素存在。 #### 插入操作 可以向集合中插入新元素,如果相同值已经存在于集合,则不会执行任何操作。例如: ```cpp #include <iostream> #include <set> using namespace std; void Print(const set<int>& s) { for(auto it = s.cbegin(); it != s.cend(); ++it){ cout << *it << " "; } cout << endl; } int main(){ set<int> s; s.insert(5); s.insert(2); s.insert(7); s.insert(4); s.insert(9); s.insert(1); Print(s); // 输出已排序后的元素序列[^2] return 0; } ``` #### 删除操作 通过指定位置或者特定数值来移除单个成员。当尝试删除不存在于集合内的项目时会返回零表示失败;成功则返回一。下面展示了如何实现这一点: ```cpp s.erase(s.begin()); // 移除第一个即最小的元素 Print(s); // 尝试移除存在的具体数值得到反馈信息 if (s.erase(2)) cout << "删除成功" << endl; else cout << "删除失败" << endl; // 对于不在集合里的数字同样处理 if (!s.erase(10)) cout << "删除失败" << endl; else cout << "删除成功" << endl; ``` #### 并集计算 为了获取两个不同集合之间的联合体而不保留中间产物可以直接采用流迭代器打印出来: ```cpp std::set<int> set1{1, 3, 5}; std::set<int> set2{2, 4, 6}; std::set_union( std::begin(set1), std::end(set1), std::begin(set2), std::end(set2), std::ostream_iterator<int>{std::cout, " "} ); ``` 上述代码片段实现了将两个整型集合合并成一个新的升序排列的结果,并逐项显示给用户查看[^1]。 #### 多重集合特性 值得注意的是,在多态版本(`multiset`)下某些原本看似无用的功能变得十分有用处,比如统计某个关键字出现次数的方法`count()`以及查找范围匹配条目的工具`equal_range()`等都得到了广泛应用场景的支持[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值