Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++, will the vector function push_back increase the size of an empty array?

Quick question. Let's say I declare a vector of size 20. And then I want to add a few integers to it using push_back.

vector<int> myVector(20);
myVector.push_back(5);
myVector.push_back(14);

Is the capacity of my vector now 22, or is it still 20? Were 5 and 14 added to indices [19] and [20], respectively? Or are they at [0] and [1]?

like image 853
iaacp Avatar asked Oct 15 '11 00:10

iaacp


People also ask

What does vector Push_back do?

C++ Vector Library - push_back() Function The C++ function std::vector::push_back() inserts new element at the end of vector and increases size of vector by one.

Does vector take more space than array?

Vector occupies much more memory in exchange for managing storage and growing dynamically, whereas Arrays are a memory-efficient data structure. Vector is derived from Collection, which contains a more generic data type, whereas Array is fixed and store a more strong data type.

Does push back increase the size of a vector?

push_back effectively increases the vector size by one, which causes a reallocation of the internal allocated storage if the vector size was equal to the vector capacity before the call.


2 Answers

After those statements its capacity is implementation-defined. (Please note that is different from its size.)


vector<int> myVector(20);

This creates a vector filled with twenty 0's. Its size is twenty, exactly, and its capacity is at least twenty. Whether or not it's exactly twenty is implementation-defined; it may have more (probably not, in practice).

myVector.push_back(5);

After this, the twenty-first element of the array is 5, and the capacity is once again implementation-defined. (If the capacity had been exactly twenty before, it is now increased in an unspecified manner.)

myVector.push_back(14);

Likewise, now the twenty-second element of the array is 14, and the capacity is implementation-defined.


If you want to reserve space, but not insert elements, you'd do it like this:

vector<int> myVector;
myVector.reserve(20); // capacity is at least twenty, guaranteed not
                      // to reallocate until after twenty elements are pushed

myVector.push_back(5); // at index zero, capacity at least twenty.
myVector.push_back(14); // at index one, capacity at least twenty.
like image 100
GManNickG Avatar answered Sep 17 '22 16:09

GManNickG


  • size is the number of elements in the vector container.
  • capacity is the size of the allocated storage space
  • push_back effectively increases the vector size by one, which causes a reallocation of the internal allocated storage if the vector size was equal to the vector capacity before the call.

More info: http://www.cplusplus.com/reference/stl/vector/

like image 26
Jean Logeart Avatar answered Sep 20 '22 16:09

Jean Logeart