Does push_back () increase the size of the vector?

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

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

Does push_back allow me to increase the size to n + 1?

vectorOfTs.push_back(T());
+3
source share
4 answers

Yes; Please note that vector<T>.capacity()is different from vector<T>.size(). The latter represents the number of elements currently in the vector, while the former represents the number of elements that correspond to the space currently allocated for the vector internal buffer.

+19
source

Nearly. If there are no exceptions, it size()will increase.

push_back(T()) : . :

  • T(), push_back , size()

  • vector , , size()

  • vector std::allocator_traits<A>::construct(m, p, v);, A - std::allocator<T>, place- new, ::new((void*)p) T(v): - vector size(), , ****, ***

    • noexcept :
  • - size() , vector ( T::~T())

+8

. , (), :

std::vector<T> vectorOfTs;
vectorOfTs.reserve(n);
// now size() == 0, capacity() >= n

vectorOfTs.push_back(T());
// now size() == 1
+4

.

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

In the above statement, in fact, you create "n" the number of new instances of type T (that is, by default, the default constructor T () will run.) Now the vector vectorOfTs contains n elements. For the above statement, the next version of the vector constructor is called.

explicit vector ( size_type n, const T& value= T(), const Allocator& = Allocator() );

So, when you drop another element into a vector, the size of the vector will be n + 1.

0
source

Source: https://habr.com/ru/post/1774264/


All Articles