set_union的几个例子[转]

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

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

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

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

例子:

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

 1 // set_union example
 2 #include <iostream>
 3 #include <algorithm>
 4 #include <vector>
 5 using namespace std;
 6 
 7 int main () {
 8   int first[] = {5,10,15,20,25};
 9   int second[] = {50,40,30,20,10};
10   vector<int> v(10);                           // 0  0  0  0  0  0  0  0  0  0
11   vector<int>::iterator it;
12 
13   sort (first,first+5);     //  5 10 15 20 25
14   sort (second,second+5);   // 10 20 30 40 50
15 
16   it=set_union (first, first+5, second, second+5, v.begin());
17                                                // 5 10 15 20 25 30 40 50  0  0
18   cout << "union has " << int(it - v.begin()) << " elements.
";
19   return 0;
20 }
 1 // set_union2 example
 2 #include <set>
 3 #include <iterator>
 4 #include <iostream>
 5 #include <algorithm>
 6 using namespace std;
 7 
 8 int main(void)
 9 {
10     set<int> a,b,c;
11     a.insert(1);
12     a.insert(6);
13     a.insert(6);
14     b.insert(2);
15     b.insert(6);
16     b.insert(9);
17 
18     //最后一个参数若使用c.begin()会产生编译错误assignment of read-only localtion.
19 
20     set_union(a.begin(), a.end(), b.begin(), b.end(), inserter(c, c.begin()));
21     copy(c.begin(), c.end(), ostream_iterator <int> (cout, " "));
22     return 0;
23 } 
 1 // set_union3 example
 2 #include <vector>
 3 #include <iterator>
 4 #include <iostream>
 5 #include <algorithm>
 6 using namespace std;
 7 
 8 int main()
 9 {
10     vector<int> a,b,c;
11     for(int e=0;e<10;e++)
12     {
13        a.push_back(e);
14        b.push_back(e+5);
15     }
16     //最后一个参数若使用c.begin(),运行时会出错“Segmentation fault (core dumped)”.
17     set_union(a.begin(),a.end(),b.begin(),b.end(),back_inserter(c));
18     copy(c.begin(), c.end(), ostream_iterator<int> (cout, " "));
19     return 0;
20 }
原文地址:https://www.cnblogs.com/MATU/p/4482092.html