C++ map - clear() Function
The C++ map::clear function is used to clear all elements of the map. This function makes the map empty with a size of zero.
Syntax
void clear();
void clear() noexcept;
Parameters
No parameter is required.
Return Value
None.
Time Complexity
Linear i.e, Θ(n)
Example:
In the example below, the map::clear function is used to clear all elements of the map called MyMap.
#include <iostream> #include <map> using namespace std; int main (){ map<int, string> MyMap; map<int, string>::iterator it; MyMap[101] = "John"; MyMap[102] = "Marry"; MyMap[103] = "Kim"; MyMap[104] = "Jo"; MyMap[105] = "Ramesh"; cout<<"Before clear() function: \nMyMap contains:\n"; for(it = MyMap.begin(); it != MyMap.end(); ++it) cout<<it->first<<" "<<it->second<<"\n"; cout<<"\nMyMap size is: "<<MyMap.size()<<"\n\n"; MyMap.clear(); cout<<"After clear() function: \nMyMap contains:\n"; for(it = MyMap.begin(); it != MyMap.end(); ++it) cout<<it->first<<" "<<it->second<<"\n"; cout<<"MyMap size is: "<<MyMap.size(); return 0; }
The output of the above code will be:
Before clear() function: MyMap contains: 101 John 102 Marry 103 Kim 104 Jo 105 Ramesh MyMap size is: 5 After clear() function: MyMap contains: MyMap size is: 0
❮ C++ <map> Library