以另一种方式读取数组2维度C ++ [英] read array 2 dimensions in another way C++
问题描述
在读取数组的输入后:
std::vector<unsigned char *> inputs(elements);
inputs
是一个二维array: inputs [3] [2]
,然后读取这个数组,值是:
the "inputs
" is a 2 dimensional array: inputs[3][2]
, then reading this array out, the values are:
inputs[0][0]=1
inputs[0][1]=2
inputs[1][0]=3
inputs[1][1]=4
inputs[2][0]=5
inputs[2][1]=6
我想把这个二维数组读成一维数组:
I would like to read this 2-dimensional array into one dimensional array:
int counter=0;
int * allElements = new int[6];
for(int i=0; i<3; i++)
for(int j=0; j<2; j++)
{
allElements[counter++] = (int)inputs[i][j];
}
这是一种将所有元素读入一维数组的传统方法,我相信如果我这样读取 allElements
的元素:
That is a traditional way of reading all of the elements into one dimensional array and I believe if I read the elements of "allElements
" this way:
for(int i=0; i<6; i++)
printf("%d ", allElements[i]);
,应为: 1 2 3 4 5 6
但是,我想将二维数组的所有元素读入1维数组,这样当我这样做:
However, I would like to read all elements of two dimensional array into the 1 dimensional array such that when I do it like this:
for(int i=0; i<6; i++)
printf("%d ", allElements[i]);
应该是: 1 3 5 2 4 6
换句话说,首先读取2维数组的所有第一个元素。
In the words, reading all of the first elements of 2 dimensional arrays first.
如何实现这种方式?
推荐答案
要做的是反向循环的顺序:
All you need to do is reverse the order of the loops:
int counter=0;
int * allElements = new int[6];
for(int j=0; j<2; j++)
for(int i=0; i<3; i++)
{
allElements[counter++] = (int)inputs[i][j];
}
这应该可以做。
这篇关于以另一种方式读取数组2维度C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!