Vector: initialization or reserve?

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

    Option 2 is better, as reserve only needs to reserve memory (3 * sizeof(T)), while the first option calls the constructor of the base type for each cell inside the container.

    For C-like types it will probably be the same.

    0 讨论(0)
  • 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<int> 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.

    0 讨论(0)
  • 2020-12-08 02:32

    Another option is to Trust Your Compiler(tm) and do the push_backs without calling reserve first. It has to allocate some space when you start adding elements. Perhaps it does that just as well as you would?

    It is "better" to have simpler code that does the same job.

    0 讨论(0)
提交回复
热议问题