'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.
Solution 1:[1]
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);
}
}
Solution 2:[2]
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.
Solution 3:[3]
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;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Daniel Zehe |
| Solution 2 | |
| Solution 3 | ZBay |
