简体   繁体   English

最简单的2D数组,使用g ++,具有一个可变维?

[英]Simplest 2D array, using g++, with one variable dimension?

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. 可变长度数组未在最新的C ++标准中实现。 You can use std::vector instead 您可以改用std::vector

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

Or, to fix for example the second dimension (to 10 in this example), you can do 或者,例如要固定第二维(在此示例中为10),您可以执行

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 根据@Chiel的评论,可以提高性能

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. 这样,您就可以将所有数据连续存储在内存中,因此访问应该与使用普通的旧C数组一样快。

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). PS:似乎最后一个声明违反了标准,因为正如@juanchopanza所述,POD数组不满足将数据存储在STL数组中的要求(它们是不可分配的)。 However, g++ compiles the above 2 declarations without any problems, and can use them in the program. 但是, g++可以毫无问题地编译上述2条声明,并且可以在程序中使用它们。 But clang++ fails though. 但是clang++失败了。

You could do something like that, but it is not a true 2D array. 您可以执行类似的操作,但这不是真正的2D数组。 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] 它基于以下一般思想:在内部,多维数组必须与以下规则有关:对于维度(n,m),您必须具有以下array2d[i, j] = array1d[j + i*m]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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM