Search code examples
c++visual-studioc++14discrete-mathematics

create union function that returns type of set<int>


I am having trouble completing a function, currently does not let my program use cout when I am calling it in main. I am trying to find an alternative way to create a function definition for:

set<int> Union(const set<int> & s0, const set<int> & s1);

which creates and returns a set that is the union of two other sets (s0 and s1). What I have written (a function trying to use set_union method from #include ) and desired output is down below:

Desired output: Given set s0 has {1,2,3,4} and set s1 has {4,5,6,7}, a new set must be created (s3 that has {1,2,3,4,5,6,7}). All help is appreciated.

#include <iostream>
#include <string>
#include <set>
#include <cassert>
#include <algorithm>
using namespace std;
set<int> Union(const set<int> & s0, const set<int> & s1);
int main(){
set<int> s0{1,2,3,4};
set<int> s1{4,5,6,7};
cout << Union(s0,s1) << endl;
}
set<int> Union(const set<int> & s0, const set<int> & s1) {
    set<int> s; 
    set_union(s0.begin(), s0.end(),
        s1.begin(), s1.end(),
        s, s.begin());
    return s;
}

Solution

  • You have to use std::set_union with std::inserter like this:

    std::set<int> Union(const std::set<int> & s0, const std::set<int> & s1) {
        std::set<int> s; 
        std::set_union(s0.begin(), s0.end(),
            s1.begin(), s1.end(),
            std::inserter(s,s.begin()));
    
        return s;
    }
    

    And you will also have to define output stream operator for std::set.

    template <typename T> 
    std::ostream& operator<<(std::ostream& os, const std::set<T>& v) 
    { 
        os << "["; 
        for (auto it : v) { 
            os << it; 
            if (it != *v.rbegin()) 
                os << ", "; 
        } 
        os << "]\n"; 
        return os; 
    } 
    

    See demo here.

    Note: For MSVC compiler, <iterator> header should be included to use std::inserter.