[英]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
,執行rows
和cols
在編譯時被稱為:
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.