Seems, that I found how to easily get normal 2D Array with contiguous memory in 2 lines of code:
template<int N, int M>
using Array2D = array<array<int, M>, N>;
Let's solve easy task of swapping min and max in Array2D
(a little of c++17):
template<int N, int M>
void printArray2D(const Array2D<N, M> &arr);
int main() {
const int N = 5;
const int M = 5;
Array2D<N, M> arr;
// random init of Array2D
generate(arr.front().begin(), arr.back().end(), []()->int {
return rand() % 100;
});
printArray2D(arr);
auto[a, b] = minmax_element(arr.front().begin(), arr.back().end());
cout << "Swap minimum and maximum: " << *a << " " << *b << endl << endl;
iter_swap(a, b);
printArray2D(arr);
return 0;
}
template<int N, int M>
void printArray2D(const Array2D<N, M> &arr) {
for (const auto &row : arr) {
for (const auto &elem : row) {
cout << std::setw(3) << elem;
}
cout << endl;
cout << endl;
}
}
I got next result in Visual Studio 2017:
41 67 34 0 69
24 78 58 62 64
5 45 81 27 61
91 95 42 27 36
91 4 2 53 92
Swap minimum and maximum: 0 95
41 67 34 95 69
24 78 58 62 64
5 45 81 27 61
91 0 42 27 36
91 4 2 53 92
Pros:
arr[2][2]
Cons:
array iterators incompatible
Questions:
Array2D
ensured by anything?Array2D
safe to use in this manner (as in example) in production code? If not, can you present good code for solving this task with minimum code overhead?According to the standard the memory should be contiguous. The 26.3.7.1 [array.overview] paragraph states (emphasis mine):
The header defines a class template for storing fixed-size sequences of objects. An array is a contiguous container. An instance of array stores N elements of type T, so that size() == N is an invariant.
Update: It appears the implementation might include the padding.
More info on the subject in these SO posts:
Is the size of std::array defined by standard?
and specifically this answer:
Is the data in nested std::arrays guaranteed to be contiguous?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With