map::clear() in C++ STL


In this article we will be discussing the working, syntax and examples of map::clear() function in C++ STL.

What is a Map in C++ STL?

Maps are the associative container, which facilitates to store the elements formed by a combination of key value and mapped value in a specific order. In a map container the data is internally always sorted with the help of its associated keys. The values in the map container are accessed by its unique keys.

What is a map::clear()?

map::clear() function is an inbuilt function in C++ STL, which is defined in  header file. clear() is used to remove all the content from the associated map container. This function removes all the values and makes the size of the container as 0.

Syntax

Map_name.clear();

Parameter

This function accepts no parameter.

Return value

This function returns nothing

Example

Input

map<char, int> newmap;
newmap[‘a’] = 1;
newmap[‘b’] = 2;
newmap[‘c’] = 3;
newmap.clear();

Output

size of the map is: 0

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main() {
   map<int, string> TP_1, TP_2;
   //Insert values
   TP_1[1] = "Tutorials";
   TP_1[2] = "Point";
   TP_1[3] = "is an";
   TP_1[4] = "education portal";
   //size of map
   cout<< "Map size before clear() function: \n";
   cout << "Size of map1 = "<<TP_1.size() << endl;
   cout << "Size of map2 = "<<TP_2.size() << endl;
   //call clear() to delete the elements
   TP_1.clear();
   TP_2.clear();
   //now print the size of maps
   cout<< "Map size after applying clear() function: \n";
   cout << "Size of map1 = "<<TP_1.size() << endl;
   cout << "Size of map2 = "<<TP_2.size() << endl;
   return 0;
}

Output

Map size before clear() function:
Size of map1 = 4
Size of map2 = 0
Map size after applying clear() function:
Size of map1 = 0
Size of map2 = 0

Updated on: 15-Apr-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements