C++ Unordered_map::empty() Function
The C++ unordered_map::empty() functionis used to check whether unordered_map is empty or not. It return a boolean value true, if the size of the map is zero, otherwise it returns false, because an Unordered_map of size zero is considered an empty Unordered_map.
Syntax
Following is the syntax of unordered_map::empty() function.
unordered_map.empty();
Parameters
This function does not accepts any parameter.
Return value
This function returns boolean values, i.e., true if map is empty; otherwise, it returns false.
Example 1
Consider the following example, where we are going to demonstrate the usage of the empty() function.
#include <iostream>
#include <unordered_map>
using namespace std;
int main(void){
unordered_map<char, int> um;
if (um.empty())
cout << "Unordered map is empty" << endl;
um.emplace('a', 1);
if (!um.empty())
cout << "Unordered map is not empty" << endl;
return 0;
}
Output
Let us compile and run the above program, this will produce the following result −
Unordered map is empty Unordered map is not empty
Example 2
In the following example, we are going to declare a two unordered_maps, one is with the elements and another one is empty and applying the empty() function.
#include <iostream>
#include <unordered_map>
using namespace std;
int main(void){
unordered_map<int, string> UnorderMap1, UnorderMap2;
UnorderMap1[1] = "Tutorials";
UnorderMap1[2] = "Points";
UnorderMap1[3] = "Tutorix";
if(UnorderMap1.empty())
cout<<"true"<<endl;
else
cout<<"false"<<endl;
if(UnorderMap2.empty())
cout<<"true"<<endl;
else
cout<<"false"<<endl;
return 0;
}
Output
Following is the output of the above code −
false true
Example 3
Let's look at the following example, where we are going to display the elemets of the map using iterator if the map is not empty orelse displaying a statement.
#include <iostream>
#include <unordered_map>
using namespace std;
int main(void){
unordered_map<int, string> UnorderMap1, UnorderMap2;
UnorderMap1[1] = "Tutorials";
UnorderMap1[2] = "Points";
UnorderMap1[3] = "Tutorix";
if(!UnorderMap1.empty())
for (auto it = UnorderMap1.begin(); it != UnorderMap1.end(); ++it)
cout<<it->first<<" = "<<it->second<<endl;
else
cout<<"Unordered map1 is empty\n";
if(UnorderMap2.empty())
cout<<"Unordered Map2 is empty\n";
else
for (auto it = UnorderMap1.begin(); it != UnorderMap1.end(); ++it)
cout<<it->first<<" = "<<it->second<<endl;
return 0;
}
Output
Output of the above code is as follows −
3 = Tutorix 2 = Points 1 = Tutorials Unordered Map2 is empty