C++ .capacity()
Published Aug 14, 2024
In C++, the .capacity() method returns the currently allocated storage space for a vector. It differs from the .size() method, which represents the current number of elements in a vector. The value of .capacity() can be equal to or greater than the value of .size(). It indicates the total number of elements that a vector can hold without requiring reallocation. This value is automatically assigned to a vector during initialization.
Syntax
The .capacity() method requires no parameters and can be used as:
myvector.capacity()
myvector: The vector on which the method is to be applied.
Example
The following example initializes two vectors and returns their capacities using the .capacity() method:
// Comparing vectors with different capacities#include <iostream>#include <vector>int main(){// Initialize two vectorsstd::vector<int> vector_1 = {1, 2, 3};std::vector<int> vector_2;// Add elements to vector_2for (int i = 0; i < 6; i++)vector_2.push_back(i);// Print the capacity of each vectorstd::cout << "Capacity of vector_1: " << vector_1.capacity() << '\n';std::cout << "Capacity of vector_2: " << vector_2.capacity() << '\n';return 0;}
The above code results in the following output:
Capacity of vector_1: 3Capacity of vector_2: 8
Learn C++ on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
- Beginner Friendly.11 hours