获得两个集合的并集。两个输入序列须保证已排好序。

数组用的时候

// 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用的时候

// 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;
}

vector用的时候

// 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;
}
05-11 08:22