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]?
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.
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.
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.
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.
size
is the number of elements in the vector container.capacity
is the size of the allocated storage spacepush_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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With