In C++, the std::map::size() is a built-in method used to find the number of elements in std::map container. It is the member function of std::map defined inside <map> header fie. In this article, we will learn about std::map::size() method in C++.
Example:
// C++ Program to illustrate the use
// of map::size() method
#include <bits/stdc++.h>
using namespace std;
int main() {
map<int, string> m = {{1, "Geeks"},
{3, "GeeksforGeeks"}, {2, "Geeksfor"}};
cout << m.size();
return 0;
}
Output
3
map::size() Syntax
m.size()
Parameters
- This function does not take any parameter.
Return Value
- Returns the number of elements in the map.
- If the map is empty, returns 0.
More Examples of map::size()
The following examples demonstrates the use of map::size() function in different scenarios:
Example 1: Checking the Size of an Empty Map
// C++ Program to find the size of the empty
// map using map::size()
#include <bits/stdc++.h>
using namespace std;
int main() {
map<int, string> m;
// Print the size of the empty map
cout << m.size() << endl;
return 0;
}
Output
0
Example 2: Size of Map after Erasing Elements
// C++ Program to illustratet the use
// of map::size() method
#include <bits/stdc++.h>
using namespace std;
int main() {
map<int, string> m = {{1, "Geeks"},
{3, "GeeksforGeeks"}, {2, "Geeksfor"}};
// Remove elements till there is only one
// element left
while(m.size() > 1)
m.erase(m.begin());
for(auto i: m)
cout << i.first << ": " << i.second;
return 0;
}
Output
3: GeeksforGeeks