Simplest 2D array, using g++, with one variable di

2019-09-07 12:57发布

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?

2条回答
beautiful°
2楼-- · 2019-09-07 13:20

Variable length arrays didn't 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 (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 old pointers,

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

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

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

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. But clang++ fails though.

查看更多
放我归山
3楼-- · 2019-09-07 13:32

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]

#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;
}
查看更多
登录 后发表回答