I would like to make an array like this:
double array[variable][constant];
Only the first dimension is variable. Declaring this with a variable as the first dimension gives initialization errors. Is there a simple way to do this with pointers or other basic types?
Variable length arrays didn't make it in the latest C++ standard. You can use
std::vector
insteadOr, to fix for example the second dimension (to 10 in this example), you can do
Otherwise you need to use old pointers,
In light of @Chiel's comment, to increase performance you can do
In this way, you have all data stored contiguously in the memory, so access should be as fast as using a plain old
C
array.PS: it seems that the last declaration is against the standard, since as @juanchopanza mentioned, POD arrays do not satisfy the requirements for data to be stored in an STL array (they are not assignable). However,
g++
compiles the above 2 declarations without any problems, and can use them in the program. Butclang++
fails though.You could do something like that, but it is not a true 2D array. It is based on the general idea that internally a multiple dimension array is necessarily linear with the rule that for an array of dimensions (n, m) you have :
array2d[i, j] = array1d[j + i*m]