gpt4 book ai didi

c++ - 生成二维 vector 中元素的所有组合

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:31:19 25 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
How can I create cartesian product of vector of vectors?

我在弄清楚如何生成二维 vector 中元素的所有组合时遇到了一些逻辑问题。在这里,我创建了一个 2D vector 。这两个维度的大小都不能假设。

#include <iostream>
#include <vector>

using namespace std;

int main() {
srand(time(NULL));
vector< vector<int> > array;

// This creates the following:
// array[0]: {0, 1, 2}
// array[1]: {3, 4, 5, 9}
// array[2]: {6, 7, 8}
for(int i=0; i<3; i++) {
vector<int> tmp;
tmp.push_back((i*3)+0); tmp.push_back((i*3)+1); tmp.push_back((i*3)+2);
if(i==1)
tmp.push_back((i*3)+6);
array.push_back(tmp);
}
}

创建 vector 后,我想输出所有可能的组合如下:

  comb[0] = {0, 3, 6}
comb[1] = {0, 3, 7}
comb[2] = {0, 3, 8}
comb[3] = {0, 4, 6}
comb[4] = {0, 4, 7}
comb[x] = {...}

但是,我在如何概念化循环结构以正确执行此操作时遇到了麻烦,其中“数组”的大小和每个子数组中的元素是未知/动态的。

编辑 1:不能假设有 3 个数组。其中有 array.size() ;)

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com