Search code examples
c++vectormemory-managementpush-back

Does push_back() always increase a vector's size?


I have a piece of code which creates a std::vector<T> with a known size:

std::vector<T> vectorOfTs(n);

Does calling push_back increase the size to n+1?

vectorOfTs.push_back(T());

Solution

  • Yes; note that vector<T>.capacity() is different from vector<T>.size(). The latter denotes the number of elements currently in the vector while the former represents the number of items that fit in the space currently allocated for the vector's internal buffer.