Simplest 2D array using g ++ with one variable size?

I would like to create an array like this:

double array[variable][constant]; 

Only the first dimension is a variable. Declaring this parameter with a variable as the first dimension gives initialization errors. Is there an easy way to do this with pointers or other basic types?

0
c ++ arrays dynamic 2d
source share
2 answers

Variable-length arrays did not make it in the latest C ++ standard. You can use std::vector instead

 std::vector<std::vector<double> > arr; 

Or, to fix, for example, the second dimension (up to 10 in this example), you can do

 std::vector<std::array<double, 10> > arr1; // to declare a fixed second dimension 

Otherwise, you need to use the old pointers,

 double (*arr)[10]; // pointer to array-of-10-doubles 

In the light of @Chiel's comment, to improve performance, you can do

 typedef double (POD_arr)[10]; std::vector<POD_arr> arr; 

That way you have all the data stored in memory in memory, so access should be as fast as when using the plain old C array.

PS: the last declaration seems to be contrary to the standard because, as mentioned by @juanchopanza, POD arrays do not satisfy the requirements for storing data in an STL array (they cannot be assigned). However, g++ compile the above 2 declarations without any problems and can use them in the program. But clang++ fails.

+1
source share

You can do something similar, but this is not a real 2D array. It is based on the general idea that an internally multidimensional array is necessarily linear with a rule, which for an array of dimensions (n, m) you have: array2d[i, j] = array1d[j + i*m]

 #include "iostream" using namespace std; class dynArray { private: double *array; int dim2; public: dynArray(int variable, int constant) { array = new double[variable * constant]; dim2 = constant; } ~dynArray() { delete array; } double value(int i, int j) { return array[j + i * dim2]; } double *pt(int i, int j) { return array + j + i * dim2; } }; int main(int argc, char*argv[]) { dynArray d(3,4); *d.pt(2,3) = 6.; cout << "Result : " << d.value(2,3) << endl; return 0; } 
0
source share

All Articles