I have a code as follows:
int n;
int get_the_number();
void some_computations();
int main()
{
     n = get_the_number();
     some_computations()
     return(0);
}
The get_the_number function get some input and returns the integer n, which after its call will not be modified.  
In the some_computation function there is the following code 
std::vector<my_struct> my_array;
for(int i=0; i<n; i++)
{ 
     my_struct struct_temp;
     // fill struct_temp;
     my_array.push_back(struct_temp);
}
Question: Since the size of my_array is known a priori, is it possible to replace the std::vector with a std::array? 
Moreover, in the affirmative case, should I expect a gain in terms of efficiency?
I tried to replace the vector declaration with
 std::array<my_struct,n> my_array;
but I get an error: the size of the array must be constant. Is there a way to avoid it?
Thank you very much.
std::array needs to know the size at compile time, which doesn't apply to your code. So no, you cannot simply replace std::vector with std::array here, unless get_the_number() can return a constexpr For example.
constexpr int get_the_number() { return 42; }
int main()
{
  std::array<int, get_the_number()> a;
}
But presumably in your case int get_the_number() obtains a number determined at runtime.
If you want to use the fact that your array length is a run time constant to improve efficiency, what you want to do is to use std::vector::reserve to reserve the necessary space ahead of time to save any reallocations as the vector grows - this should make it almost as fast as an array.
my_array.reserve(get_the_number());
some_computations()
Or if array is local to the function, pass in the number as a parameter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With