Reputation: 311
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;
}
Upvotes: 1
Views: 376
Reputation: 26810
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
.
Upvotes: 2
Reputation: 38325
If you can use C++17, there is std::set::merge
for you. Note that this member function mutates both the object it belongs to and the function argument. Hence, changing the function signature of Union
such that both sets are copied makes sense for an implementation that uses the merge
function:
std::set<int> Union(std::set<int> s0, std::set<int> s1) {
s0.merge(std::move(s1));
return s0;
}
Upvotes: 2