Vector: initialization or reserve?

前端 未结 9 659
我寻月下人不归
我寻月下人不归 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:32

    How it Works

    This is implementation specific however in general Vector data structure internally will have pointer to the memory block where the elements would actually resides. Both GCC and VC++ allocate for 0 elements by default. So you can think of Vector's internal memory pointer to be nullptr by default.

    When you call vector vec(N); as in your Option 1, the N objects are created using default constructor. This is called fill constructor.

    When you do vec.reserve(N); after default constructor as in Option 2, you get data block to hold 3 elements but no objects are created unlike in option 1.

    Why to Select Option 1

    If you know the number of elements vector will hold and you might leave most of the elements to its default values then you might want to use this option.

    Why to Select Option 2

    This option is generally better of the two as it only allocates data block for the future use and not actually filling up with objects created from default constructor.

提交回复
热议问题