问题:将多个集合合并成没有交集的集合。
给定一个字符串的集合,格式如:{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/
-
- #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);
- vector<int>::iterator it;
-
- sort (first,first+5);
- sort (second,second+5);
-
- it=set_union (first, first+5, second, second+5, v.begin());
-
- cout << "union has " << int(it - v.begin()) << " elements.\n";
- return 0;
- }
-
- #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);
-
-
-
- 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;
- }
-
- #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);
- }
-
- set_union(a.begin(),a.end(),b.begin(),b.end(),back_inserter(c));
- copy(c.begin(), c.end(), ostream_iterator<int> (cout, " "));
- return 0;
- }