VOOZH about

URL: https://www.geeksforgeeks.org/cpp/vector-capacity-function-in-c-stl/

⇱ Vector capacity() in C++ STL - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Vector capacity() in C++ STL

Last Updated : 11 Jul, 2025

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:


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


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


Output
5

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

Decrease the Capacity of Vector


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.

Comment
Article Tags: