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());
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());
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.
Almost. If there are no exceptions, then size()
will increment.
push_back(T())
could also throw an exception at various stages: see here, or summarily:
T()
construction, in which case no call to push_back
takes place, and size()
is unaffected
if the vector
needs to increase the capacity, that may throw, in which case size()
is unaffected
the vector
element will be copy or move constructed using std::allocator_traits<A>::construct(m, p, v);
, if A
is std::allocator<T>
, then this will call placement-new
, as by ::new((void*)p) T(v)
: if any of this throws the vector
's size()
is unaffected, ****unless***
noexcept
and does throw: in which case the effects are unspecifiedthe vector update's then complete - size()
will have incremented and the value will be in the vector
(even if T::~T()
)
Yes. If you instead want to reserve space, call reserve(), e.g.:
std::vector<T> vectorOfTs;
vectorOfTs.reserve(n);
// now size() == 0, capacity() >= n
vectorOfTs.push_back(T());
// now size() == 1
Yes.
std::vector<T> vectorOfTs(n);
In the above statement, actually you are constructing 'n' number of new instances of type T (i.e. default constructor T() would be triggered for each time). Now vector vectorOfTs contains n elements. The following version of the vector constructor would be invoked for the above statement.
explicit vector ( size_type n, const T& value= T(), const Allocator& = Allocator() );
So, when you push back another element into vector, size of vector would be n+1.