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_numberfunction get some input and returns the integern, which after its call will not be modified. -
In the
some_computationfunction there is the following codestd::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::arrayneeds to know the size at compile time, which doesn’t apply to your code. So no, you cannot simply replacestd::vectorwithstd::arrayhere, unlessget_the_number()can return aconstexprFor example.But presumably in your case
int get_the_number()obtains a number determined at runtime.