C++ map clear() function

C++ map clear() function is used to remove all the elements of the map container. It clears the map and sets its size to 0.

Syntax

Parameter

None

Return value

None

Example 1

Let's see a simple example to calculate the size of map before and after the clear operation.

Output:

Initial size of map before clear operation = 5
Size of map after clear opearation = 0

In the above example, a map is initialized with 5 elements. Therefore, the size of the map is 5 but after the clear operation, size becomes 0.

Example 2

Let's see a simple example to clear the elements of the map.

Output:

mymap contains:
1 : Nikita
2 : Deep
3 : Ashish

mymap contains:
4 : Rajni
5 : Sunil 

In the above example, after clear the map, we can add new elements without initialization.

Example 3

Let's see a simple example to clear the elements of the map.

Output:

m1 group has following members:
1 : Nikita
2 : Deep
3 : Ashish
m2 group has following members:
1 : Nidhi
2 : Priya
3 : Gitanjali
m3 group has following members:
1 : Rakesh
2 : Fruti
3 : Kamlesh

Which group do you want to delete?
 1. m1
 2. m2
 3. m3
 Please enter your choice: 2

Group m2 has been cleared.

In the above example, there are three groups of a map and according to the user?s choice, one group has been deleted.

Example 4

Let's see a simple example:

Output:

1. 
Fruit bucket has following fruits = 
Apple : 190
Banana : 40
Orange : 120

Do you want to clear your fruit bucket?
Press 1 for Yes and 0 for No: 0
3 fruits in bucket



2. 
Fruit bucket has following fruits = 
Apple : 190
Banana : 40
Orange : 120

Do you want to clear your fruit bucket?
Press 1 for Yes and 0 for No: 1
0 fruits in bucket

In the above example, a fruit map is initialized with three fruits. Asking for clearing the map, if you enter 0 then fruit bucket has 3 elements or if you enter 1 then it will clear the fruit map and the size becomes 0.

Next TopicC++ Map



Latest Courses