[英]Copy a 2D array to other 2D array that unknown size in C++
I have a question about dynamic 2D array returning. 我对动态2D数组返回有疑问。 That means I don't know size of returning 2D array (It depends on some condition).
这意味着我不知道返回2D数组的大小(取决于某些条件)。 Let see my problem
看我的问题
N=3;
A[N][5]={}//Given a 2D array
for i=1 to N
x=random between 0 and 1
k=1;
while(k<N&&x>0.3)
k++;
B_i=A_k //Look like copy value of array A to array B at position k
My problem is that I don't know the value of k, it depends on (k<N&&x>0.3)
. 我的问题是我不知道k的值,它取决于
(k<N&&x>0.3)
。 Hence, I cannot initial the array B. Could you suggest to me one way to do it? 因此,我无法初始化数组B。您能建议我一种方法吗? This is my code that I tried
这是我尝试过的代码
int A[2][5] =
{
{1,8,12,20,25},
{5,9,13,24,26},
{15,1,5,2,22}
};
int N=3;
for(int i=0;i<N;i++)
{
double x=random();//create random number between 0 and 1.
int k=0;
while(k<N&&x>0.3)
{
k++;
B[k][4]=A[i][4]; //I have no idea to initial 2D array B
}
}
you may use 你可以用
std::vector<std::vector<int>> B;
st::vector<int> row;
row.push_back(1);
row.push_back(2);
B.push_bak(row);
st::vector<int> row1;
row1.push_back(3);
row1.push_back(4);
B.push_bak(row1);
in this way you will get array {{1,2},{3,4}} or 这样,您将获得数组{{1,2},{3,4}}或
int** B;
B = new int*[2];
B[0]=new int[2];
B[1]=new int[2];
B[0][0] =1;
B[0][1] =2;
B[1][0] =3;
B[1][1] =4;
Maybe you could use the fact k can not become larger than N? 也许您可以使用k不能大于N的事实?
The loop 循环
while(k<N && x>0.3)
k++;
will always terminate when/if k becomes equal to N (regardless of x) so the array B should be 当/如果k等于N(无论x),它将总是终止,因此数组B应该是
int B[N+1][5];
EDIT: Just to clarify - the point is that k will alway be in the range [1..N]. 编辑:只是为了澄清-关键是k总是在[1..N]范围内。 I didn't want to state that k would always become N. Only that k could not be greater than N.
我不想声明k总是变为N。只有k不能大于N。
vector< vector<int> > A;
int N=3;
for(int i=0;i<N;i++)
{
double x=random();//create random number between 0 and 1.
int k=1;
while(k<N&&x>0.3)
k++;
B.push_back(A[i]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.