Vector: initialization or reserve?

前端 未结 9 651
我寻月下人不归
我寻月下人不归 2020-12-08 01:38

I know the size of a vector, which is the best way to initialize it?

Option 1:

vector vec(3); //in .h
vec.at(0)=var1;             


        
9条回答
  •  一生所求
    2020-12-08 02:08

    In the long run, it depends on the usage and numbers of the elements.

    Run the program below to understand how the compiler reserves space:

    vector vec;
    for(int i=0; i<50; i++)
    {
      cout << "size=" << vec.size()  << "capacity=" << vec.capacity() << endl;
      vec.push_back(i);
    }
    

    size is the number of actual elements and capacity is the actual size of the array to imlement vector. In my computer, till 10, both are the same. But, when size is 43 the capacity is 63. depending on the number of elements, either may be better. For example, increasing the capacity may be expensive.

提交回复
热议问题