How to get Cartesian product from different group

2019-09-25 08:30发布

问题:

This question already has an answer here:

  • print out all combinations of index 1 answer

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