I'm writing a small scientific computational library in my free time. And I found some people said that store a two dimension array in an one dimension array is faster and you can do it by overloading the function-all operator. But I don't know how to deal with it.
Now I think the function array should do that:
#include<iostream>
int main(){
int M=10;
int N=10;
double x[M*N];
cout<<x(m,n)<<endl;//print the m*N+n element of x
return 0;
}
How can I do with it? Or anywhere said it.I don't see it in stackoverflow....
That the x[m*N+n] is useful for two-dimension condition. But if I have four dimension, it will be x[m*A+n*B+p*C+l*D],every time I use it, I will write a long paragraph...
Ok, I shall admit that you want to write a scientific computing library and that (low level) optimization will matter. It is the only reason for me not to just say: do not worry with low level arrays and only use vectors of vectors [of vectors...]
But VLA arrays are not a C++ thing. It is a (documented) gcc extension, also supported by Clang, but other compilers will not correctly compile double x[M*N];
, and only reserve a 0 bytes array unless M
and N
are compile time constants (constexpr
).
And even for a scientific library, the overhead of a clean x[i][j]
over x[i*M + j]
is insignificant. Unless you can prove through profiling that it is both required and efficient do not go that way.
That being said the idiom x(i,j)
can be useful if you have to deal with dynamic sized multi-dimensional arrays. I once tried to build a generic library for it using the standard []
notation and it lead to a nightmare.
You will need:
a class to host a dynamic sized array for the proper dimensions (you could use a template based of the dimensions number)
a ctor with the size along all the dimensions that will allocate the underlying 1-D array - I would advise to use a vector unless you want to explicitely handle the corner cases of copy/move construction/assignment (rule of 5)
an implementation of operator()(int i, int j, ...)
with the correct number of dimensions that just returns (for dimensions K, L, M, N, and coordinates i, j, k , l):
x[l + K * (k + L * (j + M * i))]