C++ Standard Library C++ STL Library

C++ <vector> - capacity() Function



The C++ vector::capacity function returns size of currently allocated space to the vector, expressed in terms of elements. The returned value is not necessarily equal to the vector size. It can be greater than or equal to as compared to the vector size, with the extra space required for the vector to optimize its operations.

Syntax

size_type capacity() const;
size_type capacity() const noexcept;

Parameters

No parameter is required.

Return Value

Returns size of currently allocated space to the vector, measured in terms of number of elements it can hold.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the vector::capacity function is used to find out the size of currently allocated space to the vector MyVector.

#include <iostream>
#include <vector>
using namespace std;
 
int main (){
  vector<int> MyVector{10, 20, 30, 40, 50};
  vector<int>::iterator it;

  cout<<"The vector is:";
  for(it = MyVector.begin(); it != MyVector.end(); ++it)
    cout<<" "<<*it;

  cout<<"\nVector size is: "<<MyVector.size()<<"\n";
  cout<<"Vector capacity is: "<<MyVector.capacity()<<"\n";
  return 0;
}

A possible output could be:

The vector is: 10 20 30 40 50
Vector size is: 5
Vector capacity is: 5

❮ C++ <vector> Library