How to set the initial size of std :: vector?

I have a vector<CustomClass*> and I put a lot of elements into a vector and I need quick access, so I do not use a list. How to set the initial size of the vector (for example, there should be 20,000 places to avoid copying when inserting a new one)?

+69
c ++ stl
Jul 12 2018-12-12T00:
source share
2 answers
 std::vector<CustomClass *> whatever(20000); 

or

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

The first sets the actual size of the array - i.e. makes it a vector of 20,000 pointers. The latter leaves the vector blank, but leaves room for 20,000 pointers, so you can insert (up to) a lot without the need for redistribution.

You should probably know that the chances of it being really real are minimal.

+87
Jul 12 2018-12-12T00:
source share

You need to use the backup function to set the initial allocated size or to do this in the original constructor.

 vector<CustomClass *> content(20000); 

or

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

When you reserve() elements, vector will allocate enough space for (at least?) That many elements. Elements do not exist in vector , but memory is ready to use. This may speed up push_back() since memory is already allocated.

+6
Jul 12 2018-12-12T00:
source share



All Articles