I am trying to convert a 2D array into a 1D array using for loops. Am I able to accomplish this using the described method? Currently my code just assigns the final element of the 2D array to all the elements of the 1D array.
#include <iostream>
using namespace std;
int main() {
int myArray[4][2]={{1,2},{3,4},{5,6},{7,8}};
int ray[8];
for(int i=0; i<8; i ){
for(int j=0; j<4;j ){
for(int k=0;k<2;k ){
ray[i]=myArray[j][k];
}
}
}
for(int z = 0; z<8; z ){
cout << ray[z] << endl;
}
}
CodePudding user response:
The 3 for loops will copy every value in myArray
to ray
over and over overwriting the value every time until you assign myArray[3][1]
to every element of ray
.
You have to compute the value of i
based on j
and k
instead or vice versa instead of 3 nested loop.
But you can also use the fact how 2D arrays are layed out in memory. Specifically a 2D array is a single contigos block of memory. So you can just copy the whole block at once:
std::copy_n(&my_Array[0][0], 4 * 2, &ray[0]);
CodePudding user response:
Here's the example of taking advantage of the memory layout.
Basically a 2D array is just a bunch of 1-d arrays. So all we basically need to do is say going from the first 1-d array, just place the next one after it, until they are all stacked in a line.
**Memory 2-d array**
[1-d A]
[1-d B]
[1-d C]
**We just need to reshuffle**
[1-d A][1-d B][1-d C]
[1-d A] <- at the end of this guy put [1-d B]
results: [1-d A][1-d B] with length (A width) (B width)
[1-d A][1-d B] <- at the end of this guy put [1-d C]
results: [1-d A][1-d B][1-d C] with length (A width) (B width) (C width)
Example with code
int main()
{
//Create some variables so naming is easier to follow
const int rows = 4;
const int rowWidth = 2;
//Make our 2d array
int twoDArray[rows][rowWidth] = { {1,2},{3,4},{5,6},{7,8} };
//Make our one d array
int oneDDArray[rows * rowWidth] = {};
//For each row we just need to copy that block of memory in
for(int currentRow = 0; currentRow < rows; currentRow )
{
//Calculate how far we've gone th equivalent 1d distance # rows * row width
const int oneDIndex = currentRow * rowWidth;
//The next row to copy is just the next row in our for loop at the first position
//Then we copy a widths worth of memory, note we need to know how big an int memory block is hence "* sizeof(int)"
memcpy(&oneDDArray[oneDIndex], &twoDArray[currentRow][0], rowWidth * sizeof(int));
}
for (const int i : oneDDArray)
{
std::cout << i << ", ";
}
}