Adding to Vectors

In the area of vectors, I'm able to reserve() and then push_back just fine, but I thought just push_back would automatically increase the capacity. Whenever I just do push_back the capacity increases more then it should (supposed to be 14 but becomes 18. Anyways, here's the code.

#include<iostream>
#include<vector>

using namespace std;

int main()
{
//Declare Vector
vector<int> HandGunAmmo(12,1);

//State Capacity
cout << "Hand Gun Capacity = " << HandGunAmmo.capacity() << endl;

//Display Rounds
for(int index=0;index<(int)HandGunAmmo.size();++index)
{
cout << HandGunAmmo.at(index) << " ";
}
cout << endl;

//State there was an upgrade
cout << "Hand Gun Upgrade: Capacity + 2!" << endl;

//Increased size
for(int index=0;index<2;++index)
{
HandGunAmmo.push_back(1);
}

//State new capacity
cout << "Hand Gun Capacity = " << HandGunAmmo.capacity() << endl;

//Display new rounds
for(int index=0;index<(int)HandGunAmmo.size();++index)
{
cout << HandGunAmmo.at(index) << " ";
}

cin.get();

return 0;
}
reserve() is a hint to the vector to let it know how many elements you intend it to hold - it allocates memory for such but doesn't instantiate any obejcts.

push_back() instantiates an object in the next available reserved space, or if there is no more reserved space it reserves more and either copy- or move-constructs the existing elements into the new memory.

When the vector reserves memory itself automatically, it may reserve more than just one additional slot - this is intended as an optimization so that it does not have to re-allocate every time you add another element.
Last edited on
Thank you kindly. I had no idea that it made more then one slot when it did it reserved memory on its own. To keep control over capacity, I'll just need to reserve it beforehand.
You shouldn't need to be concerned about capacity unless you have intense memory constraints.
Topic archived. No new replies allowed.