生成元素的2D矢量的所有组合

编程入门 行业动态 更新时间:2024-10-27 06:20:03
本文介绍了生成元素的2D矢量的所有组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

可能重复:   How我可以创建载体载体的笛卡尔积?

我在搞清楚如何生成元素的所有组合中的2D矢量一些逻辑问题。在这里,我创建了一个二维矢量。既不尺寸的大小可以假设

I'm having some logical issues figuring out how to generate all combinations of elements in a 2d vector. Here, I create a 2D vector. Neither dimension's size can be assumed.

#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); } }

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

After creating the vector, I'd like to output all possible combinations as follows:

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] = {...}

然而,我无法如何概念化环路结构做这个正常,其中该尺寸'阵列'和每个子阵列中的元素是未知的/动态的。

However, I am having trouble how to conceptualize the loop structure to do this properly, where the size 'array' and the elements in each sub-array is unknown/dynamic.

编辑1:不能假定有3个阵列。有array.size其中())

EDIT 1: Can't assume there are 3 arrays. There are array.size() of them ;)

推荐答案

未知大小的最简单的方法就是递归。

The easiest way for unknown sizes is recursion.

void combinations(vector<vector<int> > array, int i, vector<int> accum) { if (i == array.size()) // done, no more rows { comb.push_back(accum); // assuming comb is global } else { vector<int> row = array[i]; for(int j = 0; j < row.size(); ++j) { vector<int> tmp(accum); tmp.push_back(row[j]); combinations(array,i+1,tmp); } } }

起初与调用I = 0 和一个空的 ACCUM 。

更多推荐

生成元素的2D矢量的所有组合

本文发布于:2023-11-30 06:31:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649028.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   矢量   元素

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!