In C++, the map::size() function is used to determine the total number of elements currently stored in the map container. It helps to check the current size of the map and is commonly used while traversing, validating, or processing map data
It has the following syntax:
Member type size_type is an unsigned integral type.
It returns the number of elements present in the map.
Here, we are going to discuss several examples to demonstrate the map size() Function
This example demonstrates how to calculate the total number of elements present in a map using the size() function.
Output:
Num map contains 4 elements.
Explanation:
In this example, we create a map<int, char> that contains four key-value pairs. After that, we use a size() function to print the total number of elements in the map, which is 4.
This example demonstrates how the size() function changes after inserting elements into an initially empty map.
Output:
Initial size of map = 0 Size of map after inserting elements = 5
Explanation:
In this example, we create an empty map<char, int>, and its initial size is shown as 0. After inserting five key-value pairs, the size() function shows the updated size of the map as 5.
This example demonstrates how to use the size() function with the erase() function to remove elements from a map until it becomes empty.
Output:
x => 100 y => 200 z => 300
Explanation:
In this example, we have taken a map<char, int> that contains three key-value pairs. After that, it repeatedly prints and erases the first element until the map becomes empty.
This example demonstrates how to store phone directory records in a map and display the total number of elements using the size() function.
Output:
Enter three sets of name and number: Michael 1001 Jhonson 2001 Brendon 3001 Size of phone map is:3 List of telephone numbers: Brendon 3001 Jhonson 2001 Michael 1001
Explanation:
In the above example, we have created a phone map interactively with three names. After that, it displays the total size of the phone map and all the names and their telephone numbers available in the map.
We request you to subscribe our newsletter for upcoming updates.

We deliver comprehensive tutorials, interview question-answers, MCQs, study materials on leading programming languages and web technologies like Data Science, MEAN/MERN full stack development, Python, Java, C++, C, HTML, React, Angular, PHP and much more to support your learning and career growth.
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India