Please include comments, explaining and screenshot of output. Thank you! Using t
ID: 3806310 • Letter: P
Question
Please include comments, explaining and screenshot of output. Thank you!
Using the Standard Template Library set class, write C++ functions that does the following:
(a) Returns the union of two sets as a new STL set. For simplicity, let us assume we have a set of integers. If one set has the members { 1,3,4 } and another set has the members { 1, 2, 4 } , you need to create and return a new set with the members { 1,2,3,4 } .
(b) Returns the intersection of two sets as a new STL set. If one set has the members { 1,3,4 } and another set has the members { 1, 2, 4 } , you need to create and return a new set with the members { 1,2,3,4 }
Explanation / Answer
#include<iostream>
#include<set>
using namespace std;
set<int> unio(set<int> set1,set<int> set2)
{
set<int> result; //Just push elements of both sets in this set common elements will automatically be handled
std::set<int>::iterator it;//Iterator element
for (it=set1.begin(); it!=set1.end(); ++it)
{
result.insert(*it);//Pushing elements of set 1
}
for (it=set2.begin(); it!=set2.end(); ++it)
{
result.insert(*it);//Pushing elements of set 2
}
return result;
}
set<int> interr(set<int> set1,set<int> set2)
{
set<int> result;//Store elements of set 1 that can be found in set 2
std::set<int>::iterator it;
for (it=set1.begin(); it!=set1.end(); ++it)
{
set<int>::iterator itt;
itt=set2.find(*it);
if(itt!=set2.end())//If element is found in set 2
{
result.insert(*it);//Insert is found
}
}
return result;
}
int main()
{
set<int> set1; //Set 1
set<int> set2; //Set 2
int noOfElementSet1,noOfElementSet2;
cout<<"Enter the number of elements in set 1"<<endl;
cin>>noOfElementSet1;
int iter;
cout<<" Enter elements ";
for(iter=0;iter<noOfElementSet1;iter++)
{
int val;
cin>>val;
set1.insert(val);
}
cout<<"Enter the number of elements in set 2"<<endl;
cin>>noOfElementSet2;
cout<<" Enter elements ";
for(iter=0;iter<noOfElementSet2;iter++)
{
int val;
cin>>val;
set2.insert(val);
}
set<int> unionn;
unionn=unio(set1,set2);
set<int>::iterator it;
cout<<" Union= ";
for (it=unionn.begin(); it!=unionn.end(); ++it)
{
cout<<*it<<" ";
}
set<int> inter;
inter=interr(set1,set2);
cout<<" Intersection= ";
for (it=inter.begin(); it!=inter.end(); ++it)
{
cout<<*it<<" ";
}
return 0;
}
SAMPLE OUTPUT
Enter the number of elements in set 1
3
Enter elements
1 2 4
Enter the number of elements in set 2
3
Enter elements
1 3 4
Union=
1 2 3 4
Intersection=
1 4