C++: Simple array manipulating Using 1D & 2D Arrays?

• 12-05-2012
rvbplayer123
C++: Simple array manipulating Using 1D & 2D Arrays?
Hello, I'm writing a program that inserts a 1D array into a specific location in a 2D array.
How do I insert it:

Code:

```int array[][MAX_COLS] = {{2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22 }, {4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44 }, {5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55 }, {6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66 }, {7, 14, 21, 28, 35, 42, 49, 56, 63, 70, 77 }, {8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88 }}; int insertarray[] = {3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33 }; // I need to put this into the 2 row. for (int nRows = 0; nRows < 6; nRows++ )   {   for( int nCols = 0; nCols < MAX_COLS; nCols++ )       {       cout << array[nRows][nCols] << " ";       }   cout << endl;   } ```

• 12-05-2012
Elysia
std::array<std::array<T, N>, M> My2DArray;
// Initialize 2D array...
std::array<T, N> My1DArray;
// Initialize 1D array...
My2DArray[K] = My1DArray;

T and N of 1D array must obviously agree with T and N in the 2D array.
Don't forget to include <array>.
• 12-05-2012
rvbplayer123
Thank you for your answer but I don't understand it. I'm using a loop to solve this problem
• 12-05-2012
Elysia
The reasoning is simple. Treat the array as if it were just a variable.
If you use C++ arrays, this is possible. No looping is necessary.
I would recommend some research on std::array and how to use it. Very simple. Very elegant. Very safe. Works very well with the standard library, too.
• 12-05-2012
King Mir
Regardless of using std::array or old style primative arrays, My2DArray[k] is a 1D array represending the kth row of My2DArray.

You cannot copy primative arrays, directly, nor can you copy from one type of array or other container to another using =. You must use a loop or a standard function. But this just like coppying any 1D sequence of data.

Using std::array is a good idea though.
• 12-05-2012
Elysia
You can copy or assign std::arrays directly to each other:

Code:

```#include <array> int main() {         const int N = 10;         const int M = 20;         const int K = 5;         typedef int T;         std::array<std::array<T, N>, M> My2DArray;         // Initialize 2D array...         std::array<T, N> My1DArray;         // Initialize 1D array...         My2DArray[K] = My1DArray; }```
My1DArray and My2DArray here are uninitialized, so be sure to initialize them properly before use, unlike what I do here.
This is just to show an example that compiles.
• 12-05-2012
rvbplayer123