Vector: initialization or reserve?

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

    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.

提交回复
热议问题