std::vector::resize() vs. std::vector::reserve()

后端 未结 6 725
梦谈多话
梦谈多话 2020-11-22 08:21

There is a thread in the comments section in this post about using std::vector::reserve() vs. std::vector::resize().

Here is the original c

6条回答
  •  盖世英雄少女心
    2020-11-22 08:41

    There are two different methods for a reason:

    std::vector::reserve will allocate the memory but will not resize your vector, which will have a logical size the same as it was before.

    std::vector::resize will actually modify the size of your vector and will fill any space with objects in their default state. If they are ints, they will all be zero.

    After reserve, in your case, you will need a lot of push_backs to write to element 5. If you don't wish to do that then in your case you should use resize.

    One thing about reserve: if you then add elements with push_back, until you reach the capacity you have reserved, any existing references, iterators or pointers to data in your vector will remain valid. So if I reserve 1000 and my size is 5, the &vec[4] will remain the same until the vector has 1000 elements. After that, I can call push_back() and it will work, but the stored pointer of &vec[4] earlier may no longer be valid.

提交回复
热议问题