Open In App

Vector capacity() in C++ STL

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

In C++, the vector capacity() is a built-in method used to find the capacity of vector. The capacity indicates how many elements the vector can hold before it needs to reallocate additional memory. In this article, we will learn about vector capacity() method in C++.

Let’s take a look at an example that illustrates vector capacity() method:

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

int main() {
    vector<int> v = {1, 4, 6, 7, 9};

    // Find capacity of vector
    cout << v.capacity();
  
    return 0;
}

Output
5

This article covers the syntax, usage, and common usage of vector capacity() method in C++:

Syntax of Vector capacity()

The vector capacity() is the member method of std::vector class defined inside <vector> header file.

v.capacity();

Parameters

  • This function does not require any parameter.

Return Value

  • Returns the capacity of vector as unsigned int size_t.

Examples of vector capacity()

The following examples demonstrates the use vector capacity() function for different purposes:

Find Capacity on Inserting New Elements

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

int main() {
    vector<int> v = {1, 4, 6, 7, 9};
  
  	cout << v.capacity() << endl;

    // Capacity increase on inerting elements
    v.push_back(11);
    v.push_back(13);

    // Find capacity of vector
    cout << v.capacity();
    return 0;
}

Output
5
10

Explanation: Initially the capacity of vector is 5, but on adding new elements in vector if the size exceeded current capacity, then capacity increase by double of previous capacity. So, the new capacity become 10 because previous capacity was 5.

Find Capacity on Removing Elements

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

int main() {
    vector<int> v = {1, 4, 6, 7, 9};

    // Capacity not change on removing elements
    v.pop_back();
    v.pop_back();

    // Find capacity of vector
    cout << v.capacity() << endl;
    return 0;
}

Output
5

Explanation: The capacity of vector will not decrease automatically on removing the elements from vector.

Decrease the Capacity of Vector

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

int main() {
    vector<int> v = {1, 4, 6, 7, 9};

    // Capacity not change on removing elements
    v.pop_back();
    v.pop_back();

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

    // Find capacity of vector
    cout << v.capacity() << endl;
    return 0;
}

Output
3

Explanation: Initially the capacity of vector is 5 but on removing 2 elements from vector, the capacity is still 5. So we use vector shrink_to_fit() method to decrease the capacity of vector which makes the capacity will equal to size of vector.


Next Article
Article Tags :
Practice Tags :

Similar Reads