C++ map size() Function

Last Updated : 15 May 2026

map size() Function

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

Syntax:

It has the following syntax:

Parameters

Member type size_type is an unsigned integral type.

Return value:

It returns the number of elements present in the map.

Examples of map size() Function

Here, we are going to discuss several examples to demonstrate the map size() Function

Example 1: Calculate the Size of a Map Using map::size()

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.

Example 2: Find the Initial and Updated Size of a Map

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.

Example 3: Use map::size() with the erase() Function

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.

Example 4: Store and Display a Phone Directory Using map::size()

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.


Next TopicC++ Map