Horje
How to Reduce the Capacity of a Vector to Fit Its Size in C++?

In C++, vectors are dynamic arrays that can resize themselves when more data is needed. But internally, apart from the resizing, the vector also keeps some extra space for expected elements to reduce the time complexity of insertion. The total space accounting for this extra space is called capacity.

In this article, we will learn how to reduce the capacity of the vector to its size in C++.

For Example,

Input:
myVector = {34, 67, 21, 90, 78}
myVector.capacity() = 8

Output:
myVector = {34, 67, 21, 90, 78}
myVector.capacity() = 5

Reducing the Capacity of the Vector to Fit its Size in C++

The std::vector class contains a member function named std::vector::shrink_to_fit() function that is used to shrink the capacity of the vector to its size. We can use it as shown:

myVector.shrink_to_fit();

C++ Program to Reduce the Capacity of the Vector to Fit its Size

C++

// C++ Program to Demonstrate how to shrink the vector
// capacity to fit its size
#include <iostream>
#include <vector>
  
using namespace std;
  
int main()
{
    // Creating a Vector of 20 size
    vector<int> myVector(20);
  
    // Inserting elements in the vector
    myVector = { 1, 2, 3, 4, 5, 5 };
  
    // Display the current size and capacity of vector
    cout << "Capacity: " << myVector.capacity() << endl;
  
    // Reducing the capacity of vector
    myVector.shrink_to_fit();
  
    // Display the updated size and capacity of vector
    cout << "Capacity: " << myVector.capacity() << endl;
  
    return 0;
}

Output

Capacity: 20
Capacity: 6

Time Complexity: O(1)
Space Complexity: O(1)




Reffered: https://www.geeksforgeeks.org


C++

Related
How to Find the Capacity of a Vector in Bytes in C++? How to Find the Capacity of a Vector in Bytes in C++?
How to Find and Replace All Occurrences of a Substring in a C++ String? How to Find and Replace All Occurrences of a Substring in a C++ String?
How to Reverse Iterate a Vector in C++? How to Reverse Iterate a Vector in C++?
How to Use a Range-Based for Loop with a Vector in C++? How to Use a Range-Based for Loop with a Vector in C++?
Set of Maps in C++ Set of Maps in C++

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