简体   繁体   English

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

[英]How to translate this Python partition code to C++?

I have this algorithm for generating the partitions of n: 我有这种算法来生成n的分区:

def partitions(n):
    if n == 0:
        yield []
        return
    for p in partitions(n-1):
        yield [1] + p
        if p and (len(p) < 2 or p[1] > p[0]):
            yield [p[0] + 1] + p[1:]

However I am not sure how to even go about translating this to C++, mostly because I don't know the shorthand equivalents for yield functionality or substring slices or list concatenations, etc. What's the most straightforward translation? 但是,我不确定如何将其转换为C ++,主要是因为我不知道yield功能或子字符串切片或列表串联等的简写形式。最直接的翻译是什么?

I slightly edited BLUEPIXY's answer on this post for your convenience. 为了您的方便起见,我对帖子的BLUEPIXY答案进行了略微编辑。

#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;
}

Output on ideone ideone输出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM