Open In App

How to Find the Capacity of a Vector in C++?

Last Updated : 22 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, the capacity of a vector means the amount of space allocated for the vector, so the vector can hold more elements than its size without any reallocation of space. In this article, we will learn how to find the capacity of a vector in C++.

Example:

Input:
myVector = {10,20,30};

Output:
Capacity of vector is : 4

Finding the Capacity of Vector in C++

To find the capacity of the std::vector, we can use the std::vector::capacity() function that returns the amount of space currently allocated for the vector, which is not necessarily equal to the vector size.

C++ Program to Find the Capacity of a Vector

The below example demonstrates the use of the capacity() function to find the capacity of a given vector in C++ STL.

C++




// C++ program to find the capacity of a vector
  
#include <iostream>
#include <vector>
using namespace std;
  
int main()
{
  
    // creating an emoty vector-0 default capacity
    vector<int> nums;
    cout << "Initial capacity: " << nums.capacity() << endl;
  
    // Adding elements in a vector
    nums.push_back(10);
    nums.push_back(20);
    nums.push_back(30);
  
    // Printing the capacity after inserting elements
    cout << "Capacity after Insertion: " << nums.capacity()
         << endl;
  
    return 0;
}


Output

Initial capacity: 0
Capacity after Insertion: 4

Time Complexity: O(1)
Auxilliary Space: O(1)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads