Horje
How to Increase the Capacity of a Vector in C++?

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++

// C++ Program to Demonstrate Vector Capacity Increase
#include <iostream>
#include <vector>
  
using namespace std;
  
int main()
{
    // Create vector
    vector<int> arr = { 2, 5, 7, 8 };
  
    // Print the vector's initial capacity
    cout << "Vector Initial Capacity: " << arr.capacity()
         << endl;
  
    // Reserve space for 5 elements
    arr.reserve(5);
  
    // Print the vector's increased capacity
    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




Reffered: https://www.geeksforgeeks.org


C++

Related
Find All Occurrences of an Element in a Vector Find All Occurrences of an Element in a Vector
How to Find the Size of a Vector in C++? How to Find the Size of a Vector in C++?
How to Find a Pair by Key in a Vector of Pairs in C++? How to Find a Pair by Key in a Vector of Pairs in C++?
How to Compare Two Pairs in C++? How to Compare Two Pairs in C++?
How to Find the Size of an Array Using Pointer to its First Element? How to Find the Size of an Array Using Pointer to its First Element?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
15