Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does vector::push_back increase capacity?

Tags:

c++

stdvector

I'm using a bunch of std::vectors by setting their capacity at the beginning and using push_back to slowly fill them up. Most of these vectors will have the same size (16 elements), although some might get larger. If I use push_back 16 times on a vector with size 0 and capacity 16 initially, can I be sure that capacity will be exactly 16 after the push_backs?

like image 996
zounds Avatar asked Jun 08 '26 16:06

zounds


2 Answers

Yes -- once you reserve a specific capacity, the vector will not be reallocated until you exceed the capacity you've set1. Exactly how many more items you may be able to push without reallocation isn't specified, but you are guaranteed at least that many.


  1. In particular, pointers and iterators into the vector are guaranteed to remain valid until you exceed the specified capacity.
like image 77
Jerry Coffin Avatar answered Jun 11 '26 07:06

Jerry Coffin


23.3.6.5 [vector modifiers]

void push_back(const T& x);
void push_back(T&& x);

Remarks: Causes reallocation if the new size is greater than the old capacity

Pretty much self-explanatory.

like image 37
Bartek Banachewicz Avatar answered Jun 11 '26 06:06

Bartek Banachewicz