set_union in STL

plz someone tell me how can i use set_union operation for following code..
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include<iostream>
#include<cstdlib>
#include<set>
#include<algorithm>
using namespace std;
int main()
{ 
	set<int> first;
	set<int> res;
	set<int> second;

	set<int>:: iterator it;
	int size;
	cout<<"\n enter no of elements of first set: ";
	cin>>size;
	for(int i=1;i<=size;i++)
	{
		first.insert(rand()%100);
	}
	it=first.begin();
	cout<<"\n elements of first set:\n ";
	while(it!=first.end())
	{
		cout<<*it<<" ";
		it++;
	}
	cout<<"\n enter no of elements of second set: ";
	cin>>size;
	for(int i=1;i<=size;i++)
	{
		second.insert(rand()%100);
	}
	cout<<"\n  elements of second set: \n";
	it=second.begin();
	while(it!=second.end())
	{
		cout<<*it<<" ";
		it++;
	}
	//cout<<"\n union of two sets are :\n ";

	return 0;
}
I'm not sure if std::set_union works with std::set. Instead you can just insert all the elements from the two set in another set and you will have the union.
1
2
res.insert(first.begin(), first.end());
res.insert(second.begin(), second.end());

you could use

1
2
std::vector<int> v;
std::set_union(first.begin(), first.end(), second.begin(), second.end(), back_inserter(v));

or

1
2
std::set<int> third;
std::set_union(first.begin(), first.end(), second.begin(), second.end(), inserter(third, third.end()));

although if set is the output, Peter87 is right, it's simpler to just insert.

thanks Peter and Cubbi
Last edited on
Topic archived. No new replies allowed.