STL之set_union、set_intersection、set_difference、set_symmetric_difference

需要的头文件:
algorithm

源码:

//源码比较复杂,不予列出
//有兴趣的可以参考sgi stl的源码

作用:
计算两个集合的并集、交集、差集、对称差集
通过二元仿函数我们可以取代 operator<

例子:

//例子只给出使用方法,有很多细节不予阐述
//具体细节参见 《STL源码剖析》
#include <iostream>
#include <set>
#include <algorithm>
#include <iterator>
#include <functional>
using namespace std;

template <typename T>
struct display
{
    void operator()(const T& x)
    {
        cout << x << " ";
    }
};

int main()
{
    int ia1[] = { 1, 3, 5, 7, 9, 11 };
    int ia2[] = { 1, 1, 2, 3, 5, 8, 13 };
    auto output = ostream_iterator<int>(cout, " ");

    multiset<int> S1(begin(ia1), end(ia1));
    multiset<int> S2(begin(ia2), end(ia2));

    for_each(S1.begin(), S1.end(), display<int>()); cout << endl;
    for_each(S2.begin(), S2.end(), display<int>()); cout << endl;

    auto first1(S1.begin());
    auto last1(S1.end());
    auto first2(S2.begin());
    auto last2(S2.end());
    auto ResetBeginIterator = [&]() {
        first1 = S1.begin();
        first2 = S2.begin();
    };

    //并集
    cout << "Union of S1 and S2: ";
    set_union(first1, last1, first2, last2, output); cout << endl;
    //1 1 2 3 5 7 8 9 11 13

    //重置迭代器
    ResetBeginIterator();
    //交集
    cout << "Intersection of S1 and S2:";
    set_intersection(first1, last1, first2, last2, output); cout << endl;
    //1 3 5

    //重置迭代器
    ResetBeginIterator();
    //差集
    cout << "Difference of S1 and S2 (S1-S2):";
    set_difference(first1, last1, first2, last2, output); cout << endl;
    //7 9 11 

    //重置迭代器
    ResetBeginIterator();
    //对称差集
    cout << "Symmetric difference of S1 and S2 (S1-S2):";
    set_symmetric_difference(first1, last1, first2, last2, output); cout << endl;
    //1 2 7 8 9 11 13
    //为啥会有1,因为这是stl概念中的set,与数学概念不同

    //重置迭代器
    ResetBeginIterator();
    //差集
    cout << "Difference of S2 and S1 (S2-S1):";
    set_difference(first2, last2, first1, last1, output); cout << endl;
    //1 2 8 13
    //为啥会有1,因为这是stl概念中的set,与数学概念不同
    return 0;
}

注意:
- 以上4个算法只针对其内元素呈有序状态的集合,SGL STL另外提供的hash_set/hash_multiset不适用这些算法
- 允许用户可以指定 “小于”的意义
- 当集合(set)允许重复元素存在时,并集、交集、差集、对称差集的定义,都与直观定义有一些不同。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值