How to Find the Size of a Map in Bytes in C++?
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++
// C++ program to illustrate how to find the size of a map // in bytes #include <iostream> #include <map> using namespace std; int main() { // Initialize a map map<string, int > myMap = { { "apple" , 1 }, { "banana" , 2 }, { "cherry" , 3 } }; // Calculating the size of the map int mapSize = myMap.size(); // Calculating the size of any individual element in the // map int elementSize = sizeof (myMap.begin()->first) + sizeof (myMap.begin()->second); // Calculate the size of the map in bytes int size = mapSize * elementSize; // print the size of map in bytes 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)
Contact Us