set_union的几个例子

问题:将多个集合合并成没有交集的集合。
  给定一个字符串的集合,格式如:{aaabbbccc},{bbbddd},{eeefff},{ggg},{dddhhh}要求将其中交集不为空的集合合并,要求合并完成后的集合之间无交集,例如上例应输出{aaabbbcccdddhhh},{eeefff},{ggg}。
  (1)请描述你解决这个问题的思路;
  (2)请给出主要的处理流程,算法,以及算法的复杂度
  (3)请描述可能的改进。

考虑使用泛型算法set_union( ).

OutputIterator set_union (InputIterator source1Beg, InputIterator source1End, InputIterator source2Beg, InputIterator source2End, OutputIterator destBeg)

Return value: An iterator to the end of the constructed range.

例子:

http://www.cplusplus.com/reference/algorithm/set_union/

// set_union example
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main () {
  int first[] = {5,10,15,20,25};
  int second[] = {50,40,30,20,10};
  vector<int> v(10);                           // 0  0  0  0  0  0  0  0  0  0
  vector<int>::iterator it;

  sort (first,first+5);     //  5 10 15 20 25
  sort (second,second+5);   // 10 20 30 40 50

  it=set_union (first, first+5, second, second+5, v.begin());
                                               // 5 10 15 20 25 30 40 50  0  0
  cout << "union has " << int(it - v.begin()) << " elements.\n";
  return 0;
}


// set_union2 example
#include <set>
#include <iterator>
#include <iostream>
#include <algorithm>
using namespace std;

int main(void)
{
    set<int> a,b,c;
    a.insert(1);
    a.insert(6);
    a.insert(6);
    b.insert(2);
    b.insert(6);
    b.insert(9);

    //最后一个参数若使用c.begin()会产生编译错误assignment of read-only localtion.

    set_union(a.begin(), a.end(), b.begin(), b.end(), inserter(c, c.begin()));
    copy(c.begin(), c.end(), ostream_iterator <int> (cout, " "));
    return 0;
} 


// set_union3 example
#include <vector>
#include <iterator>
#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
    vector<int> a,b,c;
    for(int e=0;e<10;e++)
    {
       a.push_back(e);
       b.push_back(e+5);
    }
    //最后一个参数若使用c.begin(),运行时会出错“Segmentation fault (core dumped)”.
    set_union(a.begin(),a.end(),b.begin(),b.end(),back_inserter(c));
    copy(c.begin(), c.end(), ostream_iterator<int> (cout, " "));
    return 0;
}


  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值