How to Increase the Capacity of a Vector in C++?
Last Updated :
06 Feb, 2024
In C++, vectors are containers that store data in contiguous memory locations and can resize themselves depending on the number of elements. In this article, we will learn how to increase the capacity of a vector in C++.
For Example,
Input: myVector.capacity() = 8
Output:
// new capacity
myVector.capacity() = 16;
Increase the Capacity of a Vector in C++
A vector’s capacity is the amount of storage it currently has, while its size is the number of elements it has. The std::vector::reserve() function is a simple method to increase the capacity of the vector. We pass the new capacity as an argument to this vector.
Note: std::vector::reserve() never reduces the capacity or size of the vector.
C++ Program to Increase the Capacity of a Vector
C++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > arr = { 2, 5, 7, 8 };
cout << "Vector Initial Capacity: " << arr.capacity()
<< endl;
arr.reserve(5);
cout << "Vector Increased Capacity: " << arr.capacity()
<< endl;
return 0;
}
|
Output
Vector Initial Capacity: 4
Vector Increased Capacity: 5
Time Complexity: O(n), as the memory will be reallocated.
Space Complexity: O(n)
We can also use the std::vector::resize() function but it will only increase the capacity of the vector if the current capacity is less than the desired capacity
Share your thoughts in the comments
Please Login to comment...