简体   繁体   English

在编译时推导出二维数组的一维

[英]Deduce one dimension of 2D array at compile time

I have the following function: 我有以下功能:

template <int size>
double** writeArray(double input[size][2]) {

    double** Points = new double*[size];

    for (int i = 0; i < size; ++i) {
        Points[i] = new double[2];
    }

    for (int i = 0; i < size; ++i) {
        Points[i][0] = input[i][0];
        Points[i][1] = input[i][1];
    }

    return Points;
}

which writes from a double[size][2] array into a dynamically allocated double ** pointer. 它从double[size][2]数组写入动态分配的double **指针。

Is there any way to deduce the size automatically, so that I could use it like that: 有没有办法自动推断出size ,以便我可以像这样使用它:

double** Points = writeArray(Test1);

instead of: 代替:

double** Points = writeArray<2>(Test1);

Yes! 是! You can actually deduce both dimensions at compile-time. 实际上,您可以在编译时推导出两个维度。 The idea is to write a template function that takes as its argument an array by reference . 我们的想法是编写一个模板函数,该函数通过引用将数组作为参数。 This prevents C++ from decaying the array type to a pointer type, which causes it to lose the array size. 这可以防止C ++将数组类型衰减为指针类型,从而导致它丢失数组大小。 Here's an example: 这是一个例子:

template <typename T, size_t M, size_t N>
    void howBigAmI(T (&array)[M][N]) {
    std::cout << "You are " << M << " x " << N << " in size." << std::endl;
}

You should be able to adapt this to fit your needs if you'd like. 如果您愿意,您应该能够根据自己的需要进行调整。

You should pass array by reference like: 您应该通过引用传递数组,如:

template <int size>
double** writeArray(const double (&input)[size][2])

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

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