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

C++ Vector size() usage and examples

C++ Vector (Container)

It returns the number of elements in the vector (vector).

Syntax

Vector (vector) "v" and the number of returned elements "n". The syntax is:

int n = v.size();

Parameters

It does not contain any parameters.

Return value

It returns the number of elements in the vector (vector).

Example1

Let's take a simple example to calculate the number of elements in a vector.

#include<iostream>
#include<vector>
using namespace std;
int main()
{
	vector<string> v{"Welcome to w3codebox","c"};
	int n = v.size();
	cout << "The size of the string is:\t" << n;
	return 0;
}

Output:

The size of the string is:2

In this example, it includes two string elements, the number of elements in the vector (vector) v calculated by the size() function.

Example2

Let's take another simple example.

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

Output:

The size of the vector is:5

In this example, the vector (vector) v containing integer values and the size() function returns the number of elements in the vector (vector).

C++ Vector (Container)