How to get Cartesian product from different group member? [duplicate]

旧街凉风 提交于 2019-12-14 00:06:13

问题


As the title mentioned, I have some problems in C++.

If I have a std::vector<std::vector<int> >tmpvec

vector < vector <int> > tmpvec = {
    {1,2,3},
    {4,5},
    {6,7,8,9},
    {10,11}
};

how can I generate all possible combination of a vector of vector

1,4,6,10

1,4,6,11

1,4,7,10

1,4,7,11

......

There are at most 48 different combination.


回答1:


You may do

bool increase(const std::vector<std::vector<int>>& v, std::vector<std::size_t>& it)
{
    for (std::size_t i = 0, size = it.size(); i != size; ++i) {
        const std::size_t index = size - 1 - i;
        ++it[index];
        if (it[index] >= v[index].size()) {
            it[index] = 0;
        } else {
            return true;
        }
    }
    return false;
}

void do_job(const std::vector<std::vector<int>>& v,
            const std::vector<std::size_t>& it)
{
    for (std::size_t i = 0; i != it.size(); ++i) {
        // TODO: manage case where v[i] is empty if relevant.
        std::cout << v[i][it[i]] << " ";
    }
    std::cout << std::endl;
}

void iterate(const std::vector<std::vector<int>>& v)
{
    std::vector<std::size_t> it(v.size(), 0u);

    do {
        do_job(v, it);
    } while (increase(v, it));
}

Live Demo



来源:https://stackoverflow.com/questions/32049360/how-to-get-cartesian-product-from-different-group-member

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!