简体   繁体   中英

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

I have 2D array arr[i][j]. Where i is the index of list while [j]= list of five elements. For example

arr[0][1,2,3,4,5]  
arr[1][6,7,9,2,1] 
...
arr[n][1,3,2,4,8]

I want to convert it into 1D so that index indicator get remove and have list of elements only. Please guide me.

a more modern and working solution could be something like this.

std::array<std::array<int,4>,3> ar;
ar[0]={2,3,4,5};
ar[1]={6,7,8,9};
ar[2]={10,11,12,13};

std::vector<int> oneD;
for(const auto& firstLayer : ar){
    for(const auto& secondLayerItem: firstLayer){
       oneD.push_back(secondLayerItem);
    }
}

Consider using a std::span to create a 1D view over the 2D array:

std::span sp(std::data(arr[0]), std::size(arr) * std::size(arr[0]));

Or simpler:

std::span sp(*arr, std::size(arr) * std::size(*arr));

Or if you already have the dimensions of the original array:

std::span sp(*arr, i * j);

Now you can view elements in sp with sp[N] . Demo: https://godbolt.org/z/ebeaEd6xn


Note, span is only a view over the original array, so any modifications on sp 's element will be reflected to the original array.

you can loop through your 2d array and push into a new 1d array

vector<vector<int>> twoD;
vector<int> oneD;
for (int i=0; i<twoD.size(); i++) {
  for(int j=0; j<twoD[i].size(); j++) {
    oneD.push_back(twoD[i][j]);
  }
}

return oneD;

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