简体   繁体   English

从C ++中具有非恒定数组大小的函数返回数组指针

[英]Return an array pointer from a function with non-constant array size in C++

I built a function to generate a random 2-d array in C++. 我构建了一个函数来在C ++中生成随机的二维数组。 I was hoping that I could set the size of the array at compile time, so I included variables for the number of rows and columns in the array. 我希望可以在编译时设置数组的大小,因此我在数组中包含了行和列数的变量。 However, when I try to compile the function, I get an error about the storage size of the array is not constant. 但是,当我尝试编译该函数时,出现关于数组的存储大小不是恒定的错误。 This seems to do with the the static keyword that I have to add to the array definition, so that I can return the pointer from the function. 这似乎与我必须添加到数组定义中的static关键字有关,以便可以从该函数返回指针。 I was not sure if there is a way around this error? 我不确定是否有解决此错误的方法? Any suggestions. 有什么建议么。

double * generate_random_array(int rows, int cols, double lower_, double upper_){

static double test_array[rows][cols];

for (int i = 0; i < sizeof test_array / sizeof test_array[0]; i++) {
    for (int j = 0; j < sizeof test_array[0] / sizeof(double); j++) {
        test_array[i][j] = generate_random_numbers(lower_, upper_);
    }
}
return(test_array);

}

You can make generate_random_array a template , enforcing rows and cols to be known at compile-time: 您可以generate_random_array一个template ,执行rowscols在编译时被称为:

template <int rows, int cols>
double* generate_random_array(double lower_, double upper_)
{
    /* ... as before ... */
}

Example usage: 用法示例:

generate_random_array<5, 10>(51.4, 66.0);

Nevertheless, you should use std::array instead of C-style arrays. 不过,您应该使用std::array而不是C样式的数组。 If you want resizable arrays, then you should use std::vector instead. 如果要调整数组的大小,则应改用std::vector

std::array example: std::array示例:

template <int rows, int cols>
auto generate_random_array(double lower_, double upper_)
{
    const auto idx = [](int x, int y){ return y * rows + x; };
    std::array<double, rows * cols> result;

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            result[idx(i, j)] = generate_random_numbers(lower_, upper_);
        }
    }

    return result;
}

Example usage: 用法示例:

auto test_array = generate_random_array<5, 10>(11.0, 66.33);

live wandbox example 现场魔盒示例

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

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