How to Find the Capacity of a Vector in Bytes in C++?
Last Updated :
05 Feb, 2024
In C++, vectors are used to store the collection of similar types of data and are able to automatically resize themself in order to accommodate more data. In this article, we will discuss how to calculate the capacity of a vector in bytes.
For Example
Input:
myVector = {10, 34, 12, 90, 1};
Output:
20 bytes
Capacity of Vectors in Bytes
In STL, there is no direct method to get the size of the vector in bytes. However, we can estimate the capacity in bytes by multiplying the capacity (number of elements the vector can hold without reallocation) by the size of each element.
- We can find the capacity of the vector by using the std::vector::capacity() function and to find the size of each element.
- We can use the sizeof operator on any of the vector elements accessed by the index.
C++ Program to Find the Capacity of Vector in Bytes
C++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > myVector = { 10, 20, 30, 40, 50 };
size_t size = sizeof (myVector[0]);
cout << "Size of Each Element in Bytes: " << size
<< " bytes" << endl;
size_t size_of_vector = myVector.capacity();
size_t size_In_Bytes = size * size_of_vector;
cout << "Capacity of Vector in bytes: " << size_In_Bytes
<< " bytes" << endl;
return 0;
}
|
Output
Size of Each Element in Bytes: 4 bytes
Capacity of Vector in bytes: 20 bytes
Time Complexity : O(1)
Space Complexity : O(1)
Share your thoughts in the comments
Please Login to comment...