簡體   English   中英

從C ++中具有非恆定數組大小的函數返回數組指針

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

我構建了一個函數來在C ++中生成隨機的二維數組。 我希望可以在編譯時設置數組的大小,因此我在數組中包含了行和列數的變量。 但是,當我嘗試編譯該函數時,出現關於數組的存儲大小不是恆定的錯誤。 這似乎與我必須添加到數組定義中的static關鍵字有關,以便可以從該函數返回指針。 我不確定是否有解決此錯誤的方法? 有什么建議么。

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);

}

您可以generate_random_array一個template ,執行rowscols在編譯時被稱為:

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

用法示例:

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

不過,您應該使用std::array而不是C樣式的數組。 如果要調整數組的大小,則應改用std::vector

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;
}

用法示例:

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

現場魔盒示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM