C ++递归联盟,交集和差异

时间:2013-03-18 06:08:05

标签: c++ recursion set-theory

这是一项家庭作业,我真的不知道该怎么做。我通常会创建v3 = v1,然后通过i增加v2,并检查v2的元素是否在v3中。如果没有,我会将它们添加到v3。但是我不能在方法之外创建v3,如果我尝试在方法中创建它,它只会重置自己。有人可以帮帮我吗?

这是我为他们提供的代码及其迄今为止的包装函数(它只是骨架):

// returns a new vector; every element in v1 and every element in v2 are also in this new vector
// if an element appears in both v1 and v2, it is only added once to the new vector
template <typename T> vector<T> vec_union(vector<T> &v1, vector<T> &v2)
{
    return v1;
}

template <typename T> vector<T> vec_union(vector<T> &v1, vector<T> &v2, unsigned i)
{
    return v1;
}

// returns a new vector; every element that is in both v1 and v2 are also in this new vector
// there are no duplicates in v1 and v2
template <typename T> vector<T> intersection(vector<T> v1, vector<T> v2)
{
    return v1;
}

template <typename T> vector<T> intersection(vector<T> v1, vector<T> v2, unsigned i)
{
    return v1;
}

// returns a new vector; every element that is in v1 but not v2 are also in this new vector
// there are no duplicates in v1 and v2
template <typename T> vector<T> difference(vector<T> v1, vector<T> v2)
{
    return v1;
}


template <typename T> vector<T> difference(vector<T> v1, vector<T> v2, unsigned i)
{
    return v1;
}

1 个答案:

答案 0 :(得分:1)

您通过发送v3模板参数并将其传递给T来创建vector,就像我在下面所做的那样:

vector<T> v3;

我已为您实施了vec_union功能。请注意以下事项: 我在函数中创建了v3。 我已返回v3,当调用者调用v3时,会生成外部代码将获得的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);
  }
}

请注意,我的回答会修改v1和v2。我认为这是你的老师所期望的,通过反复复制v1和v2来实现递归实现并不是非常低效。

您可以像这样调用vec_union:

vector<int> firstVector;
vector<int> secondVector;
vector<int> unionVector = vec_union(firstVector, secondVector);