English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ Usage and example of vector capacity()

C++ Vector (Container)

This function returns the current capacity of the vector.

Note: The capacity of the vector (vector) can be equal to or greater than the size of the vector. If it is greater than the size of the vector, it means that there is additional space reserved to accommodate other operations.

Syntax

Vector (vector) 'v' and return capacity 'c'. The syntax is:

int c = v.capacity();

Parameters

It does not contain any parameters.

Return value

It returns the current allocated capacity of the vector (vector).

Example1

Let's look at a simple example.

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

Output:

The capacity of the vector is:5

In this example, it includes the integer value and the capacity returned by the Capacity() function of the vector v.

Example2

Let's look at another simple example.

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

Output:

The capacity of the vector is:5

In this example, the vector (vector) ch contains character values, and the Capacity() function determines the capacity of the vector (vector) ch.

C++ Vector (Container)