0

after reading inputs to an array:

std::vector<unsigned char *> inputs(elements);

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];
   }

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]);

and it should be: 1 2 3 4 5 6

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]);

It should be: 1 3 5 2 4 6

In the words, reading all of the first elements of 2 dimensional arrays first.

How can I achieve this way?

1
  • 1
    Why are you using unsigned char * instead of vector<int>? Commented Nov 14, 2011 at 23:42

3 Answers 3

2

Just swap your i and j loops.

Sign up to request clarification or add additional context in comments.

Comments

1

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];
   }

That should do the trick.

Comments

0
for(int i=0; i<3; i++)
   for(int j=0; j<2; j++)
   {
      allElements[counter++] = (int)inputs[j][i];
   }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.