Open In App

How to Reduce the Capacity of a Vector in C++?

Last Updated : 22 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, the total amount of memory allocated to the vector is called the capacity of the vector. In this article, we will learn how we can reduce the capacity of a vector in C++.

The most efficient method to reduce the capacity of vector is by using vector shrink_to_fit(). Let’s take a look at a simple example:

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v(11);
    cout << "Initial Capacity: " << v.capacity() << endl;

    // Reduce the size to 7
    v.resize(7);

    // Shrink capacity of vector
    v.shrink_to_fit();

    cout << "Final Capacity: " << v.capacity();
    return 0;
}

Output
Initial Capacity: 11
Final Capacity: 7

Explanation: Initially capacity of vector is 11, but after applying vector resize(), decrease the size of vector to 7 but not capacity. So to decrease the capacity of vector we use vector shrink_to_fit() which makes capacity equal to size of vector.

There is also another method by which we can decrease the capacity of vector.

Manually by Creating Another Vector

To reduce the capacity of a std::vector, we can first resize it to the desired size and then create a new vector with the same elements but no extra capacity by copying the elements into it and swap the vectors using vector swap().

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> v(7, 11);
    cout << "Initial Capacity: " << v.capacity()
         << endl;

    // Reduce size to 5
    v.resize(5);

    // Create another vector of size 5 and copy
    // all elements
    vector<int> v1(v);

    // swap new vector with original vector
    v1.swap(v);

    cout << "Final Capacity: " << v.capacity();
    return 0;
}

Output
Initial Capacity: 7
Final Capacity: 5

Explanation: Initially the size and capacity of vector v is 7 but after using vector resize() make its size to 5 but capacity of vector v is still 7. Now we create another vector v1 with size and capacity 5 and copying all elements from original vector. On swapping both vector using vector swap() makes the capacity of vector v is 5.


Next Article
Article Tags :
Practice Tags :

Similar Reads