How to Find the Capacity of a Vector in C++?
Last Updated :
22 Feb, 2024
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++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > nums;
cout << "Initial capacity: " << nums.capacity() << endl;
nums.push_back(10);
nums.push_back(20);
nums.push_back(30);
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)
Share your thoughts in the comments
Please Login to comment...