C++ 如何将此Python分区代码转换为C++;?

C++ 如何将此Python分区代码转换为C++;?,c++,python,C++,Python,我有一个生成n的分区的算法: def分区(n): 如果n==0: 收益率[] 返回 对于分区(n-1)中的p: 产量[1]+p 如果p和(len(p)p[0]): 收益率[p[0]+1]+p[1:] 然而,我不知道如何将它翻译成C++,主要是因为我不知道函数的缩写等价或子串切片或列表连接等。什么是最直截了当的翻译?< /P> < P>我稍微编辑了BeleXY的帖子,方便您。 #include <iostream> #include <vector> void save

我有一个生成n的分区的算法:

def分区(n):
如果n==0:
收益率[]
返回
对于分区(n-1)中的p:
产量[1]+p
如果p和(len(p)<2或p[1]>p[0]):
收益率[p[0]+1]+p[1:]

然而,我不知道如何将它翻译成C++,主要是因为我不知道函数的缩写等价或子串切片或列表连接等。什么是最直截了当的翻译?< /P> < P>我稍微编辑了BeleXY的帖子,方便您。

#include <iostream>
#include <vector>

void save(std::vector<std::vector<int> > & dest, std::vector<int> const & v, int level){
    dest.push_back(std::vector<int>(v.begin(), v.begin() + level + 1));
}

void partition(int n, std::vector<int> & v, std::vector<std::vector<int> > & dest, int level = 0){
    int first; /* first is before last */
    if(0 == n){
        return;
    }
    v[level] = n;
    save(dest, v, level);

    first = (level == 0) ? 1 : v[level - 1];

    for(int i = first; i <= (n / 2); ++i){
        v[level] = i; /* replace last */
        partition(n - i, v, dest, level + 1);
    }
}

int main(int argc, char ** argv) {
    int N = 30;

    std::vector<int> vec(N);
    std::vector<std::vector<int> > partitions;
    // You could change N * N to minimize the number of relocations
    partitions.reserve(N * N);

    partition(N, vec, partitions);

    std::cout << "Partitions: " << partitions.size() << std::endl;
    for(std::vector<std::vector<int> >::iterator pit = partitions.begin(); pit != partitions.end(); ++pit) {
        std::cout << '[';
        for(std::vector<int>::iterator it = (*pit).begin(); it != (*pit).end(); ++it) {
            std::cout << *it << '\t';
        }
        std::cout << ']' << std::endl;
    }
    return 0;
}
#包括
#包括
无效保存(std::vector&dest,std::vector const&v,整数级){
目标推回(标准::向量(v.begin(),v.begin()+级别+1));
}
无效分区(int n,std::vector&v,std::vector&dest,int level=0){
int first;/*first在last之前*/
如果(0==n){
返回;
}
v[水平]=n;
保存(目标、v、级别);
第一级=(级别==0)?1:v[级别-1];

对于(int i=first;i最简单的翻译是一个向量和急切的求值。这是否是一个选项取决于
n
的大小。超过某一点,您可能需要构建一个状态机。@赵不确定我是否理解您的意思我的意思是,而不是使用
yield
生成一个元素然后,将它们全部添加到<代码> STD::vector < /代码>,然后返回。如果代码> N< /代码>太大,那么这是不可行的。所以你是说要迭代,而不是递归?递归,<代码>收益率<代码> -和Ackes,C++不协调。任何两个一起工作都很好,但是三个都在一起。有点难看。如果你想让
的功能产生
,你会希望你的函数是迭代的,因为更深层次的调用堆栈==需要跟踪更多的垃圾。如果你不在乎,只需要使用一个向量并向它添加一些东西。