How to Find the Size of a Vector in C++?
Last Updated :
06 Feb, 2024
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++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > vec = { 1, 2, 3, 4, 5, 6, 7, 8 };
cout << "Vector: " ;
for ( int num : vec) {
cout << num << " " ;
}
cout << endl;
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)
Share your thoughts in the comments
Please Login to comment...