vector capacity() function in C++ STL

The vector::capacity() function is a built-in function which returns the size of the storage space currently allocated for the vector, expressed in terms of elements. This capacity is not necessarily equal to the vector size. It can be equal to or greater, with the extra space allowing to accommodate for growth without the need to reallocate on each insertion. The capacity does not suppose a limit on the size of the vector. When this capacity is exhausted and more is needed, it is automatically expanded by the container (reallocating it storage space). The theoretical limit on the size of a vector is given by member max_size.

Syntax:

vector_name.capacity()

Parameters: The function does not accept any parameters.



Return Value: The function returns the size of the storage space currently allocated for the vector, expressed in terms of elements.

Below programs illustrate the above functions:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to illustrate the
// vector::capacity() function
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    vector<int> v;
  
    // inserts elements
    for (int i = 0; i < 10; i++) {
        v.push_back(i * 10);
    }
  
    cout << "The size of vector is " << v.size();
    cout << "\nThe maximum capacity is " << v.capacity();
    return 0;
}

chevron_right


Output:

The size of vector is 10
The maximum capacity is 16

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to illustrate the
// vector::capacity() function
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    vector<int> v;
  
    // inserts elements
    for (int i = 0; i < 100; i++) {
        v.push_back(i * 10);
    }
  
    cout << "The size of vector is " << v.size();
    cout << "\nThe maximum capacity is " << v.capacity();
    return 0;
}

chevron_right


Output:

The size of vector is 100
The maximum capacity is 128


My Personal Notes arrow_drop_up

The function of education is to teach one to think intensively and to think critically

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.