How to Find the Size of a Map in Bytes in C++?
Last Updated :
04 Mar, 2024
In C++, maps are associative containers that store a key value and a mapped value for each element and no two mapped values can have the same key values. In this article, we will explore how to find the size of the map in bytes in C++.
Example
Input:
myMap = {{“apple”, 1}, {“banana”, 2}, {“cherry”, 3}}
Output:
Size of the map in bytes is : 24 bytes
Find the Size of a Map in Bytes in C++
We have no direct method to find the size of a C++ map in bytes but we can use the std::map::size() method to find the number of elements in the map 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 Map in Bytes
The below example demonstrates how we can find the size of a map in bytes in C++.
C++
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<string, int > myMap = { { "apple" , 1 },
{ "banana" , 2 },
{ "cherry" , 3 } };
int mapSize = myMap.size();
int elementSize = sizeof (myMap.begin()->first)
+ sizeof (myMap.begin()->second);
int size = mapSize * elementSize;
cout << "Size of the map in bytes is : " << size
<< endl;
return 0;
}
|
Output
Size of the map in bytes is : 108
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...