How to Find the Size of a Vector in Bytes in C++?
Last Updated :
22 Feb, 2024
In C++, Vectors are dynamic containers that can change their size during the insertion or deletion of elements. In this article, we will explore how we can find the size of the vector in bytes in C++.
Example:
Input:
myVector = {10,20,30,40,50}
Output:
Size of the vector in bytes is : 20 bytes
Find the Size of a Vector in Bytes in C++
There is no direct method in C++ that can find the size of a vector in bytes. However, we can use the vector::size() method to find the number of elements in the vector and multiply it by the size of a single element which can be found using sizeof() operator.
C++ Program to Find the Size of a Vector in Bytes
C++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > vec = { 10, 20, 30, 40, 50 };
int vecSize = vec.size();
int elementSize = sizeof (vec[0]);
int size = vecSize * elementSize;
cout << "Size of the vector in bytes is : " << size
<< endl;
return 0;
}
|
Output
Size of the vector in bytes is : 20
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...