You create v3
by fowarding the T
template parameter and passing it to vector
like I have done below:
vector<T> v3;
I have implemented your vec_union
function for you. Note the following:
I have created v3
inside the function.
I have returned v3
, which results in a copy of v3
which the outside code will get, when the caller calls vec_union
.
template <typename T> vector<T>
vec_union(vector<T> &v1, vector<T> &v2)
{
if ( v2.empty() )
return v1;
vector<T>::iterator found = std::find(v1.begin(), v1.end(), v2.back());
if ( found == v1.end() )
{
// all good, element not already in v1, so insert it.
T value = v2.back();
v1.push_back(value);
v2.pop_back(); // remove back element
return vec_union(v1, v2);
}
else
{
// element was already in v1, skip it and call vec_union again
v2.pop_back(); // remove back element
return vec_union(v1, v2);
}
}
Note that my answer modifies v1 and v2. I assumed this is what your teacher expected in order to achieve a recursive implementation that isn't ridiculously inefficient by repeatedly copying v1 and v2 around.
You call vec_union like so:
vector<int> firstVector;
vector<int> secondVector;
vector<int> unionVector = vec_union(firstVector, secondVector);