【问题标题】:Combination of objects in c++c++中对象的组合
【发布时间】:2020-11-22 10:45:32
【问题描述】:

我想生成一个向量的向量组合。 例如:如果

std::vector<std::vector<int>> arr = {{1,2},{1,3},{1,4},{1,5}}

Comb(arr, 2) 应返回:

{
{{1,2},{1,3}},{{1,2},{1,4}}, {{1,2},{1,5}}, {{1,3},{1,4}}, {{1,3},{1,5}}, {{1,4},{1,5}}
}

(即将向量视为需要组合的对象)

下面的代码对整数进行组合,我相信我可以通过修改此代码得到我需要的:例如。通过开始将函数类型更改为 vector 因为我们必须返回向量的向量。

感谢所有对此问题感兴趣的人。

std::vector<std::vector<int>> Combinations::combs(int n, int r) {
    std::vector<bool> v(n);
    std::fill(v.end() - r, v.end(), true);
    std::vector<std::vector<int>> sol;
    do {
        std::vector<int> row;
        for (int i = 0; i < n; ++i) {
            if (v[i]) {
                row.push_back(i+1);
            }
        }
        sol.push_back(row);
    } while (std::next_permutation(v.begin(), v.end()));
    return sol;
}

【问题讨论】:

    标签: c++ algorithm vector


    【解决方案1】:
    std::vector<std::vector<std::vector<int>>> Combinations::combs(std::vector<std::vector<int>> const &vecs, int r) {
        std::vector<bool> v(vecs.size());
        std::fill(v.end() - r, v.end(), true);
        std::vector<std::vector<std::vector<int>>> sol;
        do {
            std::vector<std::vector<int>> row;
            for (int i = 0; i < vecs.size(); ++i) {
                if (v[i]) {
                    row.push_back(vecs[i]);
                }
            }
            sol.push_back(row);
        } while (std::next_permutation(v.begin(), v.end()));
        return sol;
    }
    

    【讨论】:

    • 谢谢保罗,这是一个有趣的答案。我相信对很多人都会有用。
    猜你喜欢
    • 2020-05-15
    • 2012-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多