Reputation: 10060
I built a function to generate a random 2-d array in 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. 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);
}
Upvotes: 1
Views: 235
Reputation: 93294
You can make generate_random_array
a template
, enforcing rows
and cols
to be known at compile-time:
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. If you want resizable arrays, then you should use std::vector
instead.
std::array
example:
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);
Upvotes: 6