1

In below program, I just create an empty vector, then resize to 5 elelemnts, and then to 8 elements.

However after resizing it to 8 elements, the capacity is shown as 10. Why is the capacity 10 and not 8 after the last resize ?

Below is the code. I have commented where the issue is.

//This program has vector method resize()
//2015-12-05 Sat 12:06 AM
using namespace std;
#include<iostream>
#include<vector>

int main()
{
    vector<int> vec1;
    //Initial empty vector
    cout << "Printing what an empty vector has..." << endl;
    cout << "Size: " << vec1.size() << endl;
    cout << "Capacity: " << vec1.capacity() << endl;       
    cout << endl << endl;

    //Resize to 5, without giving any value.
    cout << "Printing after resizing to 5 elements..." << endl;
    vec1.resize(5);
    cout << "Size: " << vec1.size() << endl;
    cout << "Capacity: " << vec1.capacity() << endl;
    cout << endl << endl;

    //Resize to 8, with value also this time
    //ISSUE HERE, WHY IS CAPACITY PRINTED AS '10', instead of '8'
    cout << "Printing after resizing to 8, and also giving values..." << endl;
    vec1.resize(8, 15);
    cout << "Size: " << vec1.size() << endl;
    cout << "Capacity: " << vec1.capacity() << endl;
    cout << endl;
    return 0;
}

Below is the output:

user $ ./a.out 
Printing what an empty vector has...
Size: 0
Capacity: 0
Elements: 

Printing after resizing to 5 elements...
Size: 5
Capacity: 5
Elements: 0 0 0 0 0 

Printing after resizing to 8, and also giving values...
Size: 8
Capacity: 10
Elements: 0 0 0 0 0 15 15 15 
user $
sps
  • 2,720
  • 2
  • 19
  • 38

1 Answers1

3

If the requested size is bigger than the current capacity, the capacity is usually doubled until it's large enough. This doubling of the size is what keeps the amortized cost of growing at O(1).

Buddy
  • 10,874
  • 5
  • 41
  • 58