Vector: initialization or reserve?

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

    Both variants have different semantics, i.e. you are comparing apples and oranges.

    The first gives you a vector of n default-initialized values, the second variant reserves the memory, but does not initialize them.

    Choose what better fits your needs, i.e. what is "better" in a certain situation.

提交回复
热议问题