How to set initial size of std::vector?

后端 未结 2 1164
暖寄归人
暖寄归人 2020-12-13 05:33

I have a vector and I put a lot of items in the vector and I need fast access, so I don\'t use list. How to set initial size of vector (for

相关标签:
2条回答
  • 2020-12-13 05:42
    std::vector<CustomClass *> whatever(20000);
    

    or:

    std::vector<CustomClass *> whatever;
    whatever.reserve(20000);
    

    The former sets the actual size of the array -- i.e., makes it a vector of 20000 pointers. The latter leaves the vector empty, but reserves space for 20000 pointers, so you can insert (up to) that many without it having to reallocate.

    At least in my experience, it's fairly unusual for either of these to make a huge difference in performance--but either can affect correctness under some circumstances. In particular, as long as no reallocation takes place, iterators into the vector are guaranteed to remain valid, and once you've set the size/reserved space, you're guaranteed there won't be any reallocations as long as you don't increase the size beyond that.

    0 讨论(0)
  • 2020-12-13 06:03

    You need to use the reserve function to set an initial allocated size or do it in the initial constructor.

    vector<CustomClass *> content(20000);
    

    or

    vector<CustomClass *> content;
    ...
    content.reserve(20000);
    

    When you reserve() elements, the vector will allocate enough space for (at least?) that many elements. The elements do not exist in the vector, but the memory is ready to be used. This will then possibly speed up push_back() because the memory is already allocated.

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