Open In App

How to Find the Size of a Vector in C++?

Last Updated : 06 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, vectors in C++ are dynamic arrays that can grow or shrink in size as elements are added or removed. In this article, we will learn how to find the size of a vector in C++.

Example

Input: myVector = {1, 2, 3, 4, 5, 6, 7, 8}

Output : Size of the vector: 8

Find the Size of the Vector in C++

In C++, the vector contains keep track of their size themselves. We can simply use the std::vector::size() member function of the std::vector class to get the size of the vector container. It returns the size i.e. number of elements present in the vector in the form of an integer.

C++ Program to Find the Size of the Vector

C++




// C++ Program to Print Size of a Vector
  
#include <iostream>
#include <vector>
  
using namespace std;
  
int main()
{
    // Initialize a vector
    vector<int> vec = { 1, 2, 3, 4, 5, 6, 7, 8 };
  
    // Print the elements of the vector
    cout << "Vector: ";
    for (int num : vec) {
        cout << num << " ";
    }
    cout << endl;
  
    // Find the size of the vector
    cout << "Size of the Vector: " << vec.size() << endl;
  
    return 0;
}


Output

Vector: 1 2 3 4 5 6 7 8 
Size of the Vector: 8

Time complexity: O(1)
Auxilary space : O(1)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads