Open In App

map clear() in C++ STL

Last Updated : 19 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

The map clear() function in C++ is used to remove all elements from the map container and make its size to 0. In this article, we will learn about the map clear() function in C++.

Let’s take a quick look at a simple example that uses map clear() method:

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    map<int, char> m = {{1, 'A'},
                        {2, 'C'},
                        {3, 'B'}};

    // Reamove all elments from map
    m.clear();

    cout << m.size();
    return 0;
}

Output
0

Explanation: Initially the size of map container is 3, but after applying map clear() function, it removes all key value pairs from the map and make its size to 0.

This article covers the syntax, usage, and common queries of map clear() method in C++:

Syntax of map clear()

The map clear() is the member function of map defined inside <map> header file.

m.clear();

where, m is the name of map container.

Parameters

  • This function does not require any parameter.

Return Value

  • This function does not return any value.

Examples of Map clear()

The following examples demonstrates the use of map clear() function in different scenarios:

Remove All Elements from Map

C++
#include <bits/stdc++.h>
using namespace std;

int main() {

    map<int, string> m = {{1, "India"}, {2, "Nepal"},
                         {3, "Sri Lanka"}, {4, "Myanmar"}};

    // Remove all elements from map
    m.clear();

    cout << m.size() << endl;
    return 0;
}

Output
0

Applying Map clear() Method on Empty Map

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    map<int, string> m;

    m.clear();

    cout << m.size() << endl;
    return 0;
}

Output
0

Explanation: Since there are no elements present in the map, so map clear() function does nothing on the map container.


Next Article
Article Tags :
Practice Tags :

Similar Reads