STL中set求交集、并集、差集的方法

并集(http://zh.cppreference.com/w/cpp/algorithm/set_union)

交集(http://zh.cppreference.com/w/cpp/algorithm/set_intersection)

差集(http://zh.cppreference.com/w/cpp/algorithm/set_difference)

 

inserter(http://zh.cppreference.com/w/cpp/iterator/inserter)

 

 back_inserter(http://zh.cppreference.com/w/cpp/iterator/back_inserter)

#include <bits/stdc++.h>
using namespace std;
const int maxn = 123;
int n;
int num[maxn];
int main(){
    set<int> a, b;
    vector<int> c;
    a =   {2,  4,   6};
    b = {1,2,3,4,5};
    //传入的a,b不一定是set, 但一定要有序
    set_union(a.begin(), a.end(), b.begin(), b.end(), back_inserter(c));//并集
    for(int n : c) cout << n << " "; puts("");
    c.clear();



    set_intersection(a.begin(), a.end(), b.begin(), b.end(), back_inserter(c));//交集
    for(int n : c) cout << n << " "; puts("");
    c.clear();

    set_difference(a.begin(), a.end(), b.begin(), b.end(), back_inserter(c)); //差集(b中属于a的元素去掉)
    for(int n : c) cout << n << " "; puts("");
    c.clear();
}

 

 

转载于:https://www.cnblogs.com/Jadon97/p/8320926.html

在C++,我们可以使用STL(Standard Template Library)提供的容器如set或unordered_set来操作集合的交集并集、补集、差集和对称差集。这里简述一下基本的概念: 1. **交集Intersection)**:两个集合的元素都存在的部分,可以使用`std::set_intersection`函数,或者直接用迭代器遍历两个集合,比较每个元素是否都在另一个集合。 ```cpp std::set<int> A = {1, 2, 3, 4}; std::set<int> B = {3, 4, 5, 6}; std::set<int> intersection; std::set_intersection(A.begin(), A.end(), B.begin(), B.end(), inserter(intersection, intersection.begin())); ``` 2. **并集(Union)**:两个集合的所有元素合并在一起,可以用`std::merge`函数或直接将两个集合相加。 ```cpp union(A, B); // 直接赋值操作 intersection.clear(); // 清空交集后添加结果 ``` 3. **补集(Complement)**:第一个集合不包含在第二个集合的元素,需要创建一个新的集合来存储,然后遍历第一个集合删除已存在元素。 ```cpp std::vector<int> complement(A.begin(), A.end()); std::set_difference(B.begin(), B.end(), complement.begin(), complement.end(), inserter(complement, complement.begin())); ``` 4. **差集(Difference)**:第一个集合特有的元素,同样需要创建新集合并从第一个集合移除出现在第二个集合的元素。 ```cpp std::set_difference(A.begin(), A.end(), B.begin(), B.end(), inserter(diff, diff.begin())); ``` 5. **对称差集(Symmetric Difference)**:返回两个集合独有的元素,既不在其一个集合而在另一个集合的元素。 ```cpp std::set_symmetric_difference(A.begin(), A.end(), B.begin(), B.end(), inserter(symmetric_diff, symmetric_diff.begin())); ``` 6. **幂集(Power Set)**:生成所有可能的子集,包括空集和原集合本身,这通常通过递归或回溯算法实现,C++标准库没有提供直接操作功能,需要自定义算法。 上述代码展示了基本的操作,实际使用时记得处理可能出现的异常,并确保数据类型匹配。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值