简体   繁体   中英

How to convert 2D array to 1D in C++?

So for example I have a 2D array A={{1,2,3}, {2,3},{5}}; and I want to get all the rows existing in the array A. I have the length of array stored in variable "lenA", here lenA=3. Also I have an Array B which has the length of each subarray in A. Say B={3,2,1} in this case. In reference to my example array A, how to I dynamically get 3 subarrays from one 2D array ie A? So as a result I would have something like:

A1={1,2,3}
A2={2,3}
A3={5}

You can't dynamically generate new identifiers in C++. The closest you can get is using the preprocessor to generate your names, and by definition, that's done before compilation.

If you already have a fixed number of named array pointers, you could assign those dynamically. But any solution that must accept an arbitrary number of rows at runtime will require that you use something like an array index.

for (int i = 0; i < lenA; i++)
{
    // Do something with the row at A[i]
}

Pseudo code

for i in 0 to lenA-1
    for j in 0 to lenB[i]-1
        A[i][j] whatever...

My try converting A(4x4) to triangle *a[4]:

#include <iostream>
#include <algorithm>
int main()
{
   constexpr int lenA = 4;
   double A[lenA][lenA]={{1,2,3,4}, {5,6, 7, 0}, {8, 9,0,0},{10,0,0,0}};
   double *a[lenA];
   int B[lenA] = {4, 3, 2, 1};

   for (int i=0; i < lenA; i++)
    {
       a[i] = new double [ B[i] ];
       std::copy_n(A[i], B[i], a[i]);
    }
   for (int i=0; i<lenA; i++) {
       std::cout << "row " << i << ": ";
       for (int j=0; j<B[i]; j++) {
           std::cout << a[i][j] << ".  ";
           }
       std::cout <<std::endl;
      }
   return 0;
}

result:

$ ./a.exe
 row 0: 1.  2.  3.  4.
 row 1: 5.  6.  7.
 row 2: 8.  9.
 row 3: 10.

you can find the verification of the below code at http://cpp.sh/57pi2

A1D represent the 1-Dimensional array which you was looking for,

#include <iostream>

int main()
{
    const int lenA = 4;
    double A2D[][lenA]={{1,2,3,4},{5,6,7},{8,9},{10}};
    double *A1D;
    int B[lenA] = {4,3,2,1};

    int num_of_elements = 0; 
    for (int i=0; i < lenA; i++)
        num_of_elements += B[i];
    
    A1D = new double[num_of_elements]   ; 
    for (int i=0, k=0; i<lenA; i++) 
        for (int j=0; j<B[i]; j++)
            A1D[k++] = A2D[i][j];

    for (int j=0; j<num_of_elements; j++)
        std::cout << A1D[j] << std::endl;
}

std::ranges in C++20 or ranges library ( C++14 compliant) does it in clean way:

    double A[][4] {
        { 1, 2, 3, 4}, 
        { 5, 6, 7, 0}, 
        { 8, 9, 0, 0},
        {10, 0, 0, 0}
    };
    for (auto x : std::ranges::views::join(A))
        std::cout << x << '\n';

https://godbolt.org/z/hPP7e9

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM