Home »
C++ STL
vector::size() function with example in C++ STL
C++ STL vector::size() function: Here, we are going to learn about the size() function of vector header in C++ STL with example.
Submitted by IncludeHelp, on May 13, 2019
C++ vector::size() function
vector::size() is a library function of "vector" header, it is used to get the size of a vector, it returns the total number of elements in the vector.
Note: To use vector, include <vector> header.
Syntax
Syntax of vector::size() function
vector::size();
Parameter(s)
none – It accepts nothing.
Return value
size_type – It returns the size as an unsigned integral type.
Sample Input and Output
Input:
vector<int> vector1{ 1, 2, 3, 4, 5 };
Function call:
cout << vector1.size();
Output:
5
C++ program to demonstrate example of vector::size() function
//C++ STL program to demonstrate example of
//vector::size() function
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v1;
//printing the size of the vector
cout << "Total number of elements: " << v1.size() << endl;
//pushing elements
v1.push_back(10);
v1.push_back(20);
v1.push_back(30);
v1.push_back(40);
v1.push_back(50);
//printing the size of the vector
cout << "Total number of elements: " << v1.size() << endl;
return 0;
}
Output
Total number of elements: 0
Total number of elements: 5
Reference: C++ vector::size()