Please include comments, explaining. Thank you! Using the Standard Template Libr
ID: 3805475 • Letter: P
Question
Please include comments, explaining. 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
Code for intersection of 2 sets using C++
#include <iostream> // standard for cout
#include <algorithm> // for set intersection and sort
#include <vector> // for vector
int main () {
int first_set[] = {1,3,4};
int second_set[] = {1,2,4};
std::vector<int> v(10);
std::vector<int>::iterator ite;
std::sort (first_set,first_set+3); // 1 3 4
std::sort (second_set,second_set+3); // 1 2 4
ite=std::set_intersection (first_set, first_set+3, second_set, second_set+3, v.begin());
v.resize(ite-v.begin()); // 1 , 4
std::cout << "The given intersection set has " << (v.size()) << " values: ";
for (ite=v.begin(); ite!=v.end(); ++ite)
std::cout << ' ' << *ite;
std::cout << ' ';
return 0;
}
Code for Union of 2sets using C++
#include <iostream> // standard for cout
#include <algorithm> // for set intersection and sort
#include <vector> // for vector
int main () {
int first_set[] = {1,3,4};
int second_set[] = {1,2,4};
std::vector<int> v(10);
std::vector<int>::iterator ite;
std::sort (first_set,first_set+3); // 1 3 4
std::sort (second_set,second_set+3); // 1 2 4
ite=std::set_union (first_set, first_set+3, second_set, second_set+3, v.begin());
v.resize(ite-v.begin()); // 1 2 3 4
std::cout << "The given union set has " << (v.size()) << " values ";
for (ite=v.begin(); ite!=v.end(); ++ite)
std::cout << ' ' << *ite;
std::cout << ' ';
return 0;
}