Vector size() function in C++

Hi folks! In this tutorial we are going to learn and focus on what are vectors and about a special function associated with vectors ie. vector size().

What are vectors?

They are dynamic arrays that can resize themselves whenever an element is inserted or deleted from it.

vector size() function

vector::size function is a function associated with vectors. This function allows you to find the number of elements in a vector. In short, we can say it returns the size of the vector.

There are no parameters required in the size function. vector size() function returns an integer value . Time complexity is big o(1).

syntax:- vector_name.size()

Let’s understand this function using a code as an example:

C++ Code: vector size()

Read the comments in the code for better understanding.

#include<iostream>
#include<vector>    
using namespace std;
int main()
{ 
    // declare name of variable as num
    vector<int>num; 
    // insert 5 numbers using push_back function
    num.push_back(3);  
    num.push_back(5);
    num.push_back(7);
    num.push_back(9);
    num.push_back(11);
    cout<<num.size(); 
    return 0;
  
 }

Output:

5

Explanation of the code

The code written above demonstrates the example of size() function. First, declare the name of the vector. Then using push_back() we will insert the elements in the vector, 5 elements are inserted and the size function() will return an integer value which indicates the size of the vector as output.

Note: Don’t forget to add the vector header file.


That’s it! Hope you found this helpful.

Leave a Reply

Your email address will not be published.