Open In App

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

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

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++




// C++ program to find the size of a vector in bytes
#include <iostream>
#include <vector>
using namespace std;
  
int main()
{
    // Initialize a vector with few elements
  
    vector<int> vec = { 10, 20, 30, 40, 50 };
  
    // Calculate the size of the vector
    int vecSize = vec.size();
    // Calculate the size of any individual element in the
    // vector
    int elementSize = sizeof(vec[0]);
    // Calculate the size of the vector in bytes
    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)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads