Vectors capacity

How does capacity in the vector class work? I don't understand why it increases if you add enough new items in the array. For example:

#include <iostream>
#include <vector>

using namespace std;

int main()
{

vector<int>numbers;

int capacity = numbers.capacity();

for (int i = 0; i < 10000; i++)
{
numbers.push_back(i);

if (capacity != numbers.capacity())
{
capacity = numbers.capacity();
cout << "Capacity: " << capacity << endl;
}
}



return 0;
}

This program outputs a few numbers every once in a while, when the size of the numbers vector increases 10000 times.
Last edited on
When you create a vector, an amount of memory is allocated for it to use. The items you put in the vector go in that memory. That memory is big enough for how many items? For capacity items.


What happens if you fill up all that memory, and then you want to add more items? More memory has to be allocated for putting those extra items in. So more memory is allocated. Now how many items could go in it? More. The capacity has increased.
Topic archived. No new replies allowed.