Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace `std::vector` with `std::array`

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.

like image 822
888 Avatar asked Dec 06 '12 08:12

888


2 Answers

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.

like image 132
juanchopanza Avatar answered Sep 20 '22 23:09

juanchopanza


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.

like image 23
Karthik T Avatar answered Sep 16 '22 23:09

Karthik T