Vector Capacity Function - C++ Programming Tutorial
C++ Course / STL Vector / Vector Capacity Function

Vector Capacity Function

BLUF: Mastering Vector Capacity Function is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Vector Capacity Function

C++ is renowned for its efficiency. Learn how Vector Capacity Function enables low-level control and high-performance computing in the tutorial below.

C++ Vector capacity

This function calculates the present size of the vector.

Note: Capacity of the vector can be equal or greater than the size of the vector and if it is greater than the size of the vector, means allowing extra space to accommodate further operations.

Syntax

Consider a vector denoted as 'v' and a capacity denoted as 'c'. The syntax is as follows:

Example

int c=v.capacity();

Parameter

It does not contain any parameter.

Return value

It provides the present allocated capacity of the vector.

Example 1

Let's see a simple example.

Example

#include<iostream>
#include<vector>
using namespace std;
int main()
{
	vector<int> v{1,2,3,4,5};
	int c=v.capacity();
	cout<<"Capacity of the vector is :"<<c;
	return 0;
}

Output:

Output

Capacity of the vector is :5

In this illustration, vector v holds integer values, and the capacity method determines the capacity of the vector v.

Example 2

Let's see a another simple example.

Example

#include<iostream>
#include<vector>
using namespace std;
int main()
{
	vector<char>ch{'j','a','v','a'};
	int c=ch.capacity();
	cout<<"Capacity of the vector is :"<<c;
	return 0;
}

Output:

Output

Capacity of the vector is :5

In this instance, the vector ch holds character values, and the capacity method is responsible for indicating the capacity of the vector ch.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience