如何编写泛型函数来计算递归组合

时间:2012-08-17 21:58:42

标签: c++ generics recursion combinations

例如:

< 1,2,3>作为函数梳的输入以获得2个元素的组合将输出结果<< 1,2>,< 1,3>,< 2,3>>,作为相同函数的输入将获得 <<< 1,2>,< 1,3>>,<< 1,3>,< 2,3>>,<< 1,2>,&2 ,3>>,作为同一函数的输入将得到 ....

逻辑是相同的,只有类型更改,因此它可以是通用的。 我试着写这样的东西:

template<typename V>
vector<vector<vector<V>::const_iterator>> comb(const vector<V>){
   ....

   while(next_combination(...))
   vector<vector<vector<V>::const_iterator>> results;
   return results;
}

vector<string> input
comb(comb(comb(input)));

但编译器继续抱怨不能推断出返回值的类型。

感谢。

1 个答案:

答案 0 :(得分:1)

也许以下内容会有所帮助:

template <typename T>
vector<vector<T> > comb(vector<T> v)
{
    vector<vector<T> > result;
    // may want to sort the input vector before iterating over the combinations
    do {
        result.push_back(v);
    } while (next_combination(...));
    return result;
}

请注意更改:

  • comb的返回值是向量的向量
  • comb的参数不是const因为next_combination更改
  • comb内的向量复制很多;所有复制似乎都是必要的