Initializing the size of a C++ vector

前端 未结 4 1248
孤城傲影
孤城傲影 2020-12-02 09:32

What are the advantages (if any) of initializing the size of a C++ vector as well as other containers? Is there any reason to not just use the default no-arg constructor?

4条回答
  •  臣服心动
    2020-12-02 10:06

    It is a bad example of Bjarne Stroustrup. Instead of the second definitiona

    vector phone_book(1000);
    

    it would be much better to write

    vector phone_book;
    phone_book.reserve( 1000 );
    

    There is no general "good ways" to determine what a good size to start off would be. It depends on the information you possess about the task. But in any case you can use some initial allocation if you are sure that new elements will be added to the vector.

提交回复
热议问题