Last Updated : 11 Jul, 2025
In C++, the vector capacity() is a built-in method used to find the capacity of vector. The capacity indicates how many elements the vector can hold before it needs to reallocate additional memory. In this article, we will learn about vector capacity() method in C++.
Let’s take a look at an example that illustrates vector capacity() method:
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {1, 4, 6, 7, 9};
// Find capacity of vector
cout << v.capacity();
return 0;
}
This article covers the syntax, usage, and common usage of vector capacity() method in C++:
Syntax of Vector capacity()The vector capacity() is the member method of std::vector class defined inside <vector> header file.
Parametersv.capacity();
The following examples demonstrates the use vector capacity() function for different purposes:
Find Capacity on Inserting New Elements C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {1, 4, 6, 7, 9};
cout << v.capacity() << endl;
// Capacity increase on inerting elements
v.push_back(11);
v.push_back(13);
// Find capacity of vector
cout << v.capacity();
return 0;
}
Explanation: Initially the capacity of vector is 5, but on adding new elements in vector if the size exceeded current capacity, then capacity increase by double of previous capacity. So, the new capacity become 10 because previous capacity was 5.
Find Capacity on Removing Elements C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {1, 4, 6, 7, 9};
// Capacity not change on removing elements
v.pop_back();
v.pop_back();
// Find capacity of vector
cout << v.capacity() << endl;
return 0;
}
Explanation: The capacity of vector will not decrease automatically on removing the elements from vector.
Decrease the Capacity of Vector C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {1, 4, 6, 7, 9};
// Capacity not change on removing elements
v.pop_back();
v.pop_back();
// Decrease capacity of vector
v.shrink_to_fit();
// Find capacity of vector
cout << v.capacity() << endl;
return 0;
}
Explanation: Initially the capacity of vector is 5 but on removing 2 elements from vector, the capacity is still 5. So we use vector shrink_to_fit() method to decrease the capacity of vector which makes the capacity will equal to size of vector.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4