【发布时间】:2011-12-23 19:48:38
【问题描述】:
可能重复:
How can I create cartesian product of vector of vectors?
我在弄清楚如何在二维向量中生成所有元素组合时遇到了一些逻辑问题。在这里,我创建了一个 2D 矢量。两个维度的大小都不能假设。
#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);
}
}
创建向量后,我想输出所有可能的组合如下:
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() ;)
【问题讨论】:
-
我可能可以帮助你,但请解释更多mathematically你的实际意思。
-
它可能是一个carthesian产品吗?对于 5 个数组 ABCDE 作为输入,您是否期望 a 来自 A、b 来自 B 等所有可能的 5 元组 (abcde)?
标签: c++ algorithm combinations