C++ Map Empty Function

In the C++ programming language, the Standard Template Library (STL) is a powerful collection of data structures and algorithms that can be leveraged by users. The map is one of the most common associative containers of the STL. A map contains items stored as pairs of keys and values, where keys must be unique and will always be sorted by the provided comparator function.

In C++, the map empty function is used to check whether the map container is empty or not. It returns true if the map container is empty (size is 0); otherwise, it returns false.

  • Keys must be unique, while values can appear multiple times.
  • The elements in the map will always be sorted by their keys, based on the comparator provided (which defaults to the std::less function).
  • Syntax:

It has the following syntax:

Example

bool empty() const; // until C++ 11  

bool empty const noexcept; //since C++ 11

In this syntax,

  • Parameter: It has no parameters
  • Return value: It returns true if the map container is empty (size is 0); otherwise, it returns false.
  • C++ Simple map empty function Example

Let us take an example to check if a map contains any element or not in C++.

Example

Example

#include <map>  

#include <iostream>  

using namespace std;    //using standard namespace

int main()    //main function

{  

    map<int,int> numbers;  

    cout <<"Initially, numbers.empty(): " << numbers.empty() << "\n";  

    numbers[1] = 100;  

    numbers[2] = 200;  

    numbers[3] = 300;  

    cout <<"\nAfter adding elements, numbers.empty(): " << numbers.empty() << "\n";  

}

Output:

Output

Initially, numbers.empty(): 1

After adding elements, numbers.empty(): 0

Explanation:

In this example, we have taken a map that has no elements. After that, the empty function returns 1(true), and after adding elements, it returns 0(false).

Checking if a C++ Map is Empty using the empty function

Let us take an example to check whether a map is empty or not using the empty function in C++.

Example

Example

#include <iostream>  

#include <map>  

using namespace std;   //using standard namespace

int main(void) {     //main function

   map<char, int> m;  

     if (m.empty())  

      cout << "Map is empty." << endl;  

     m['n'] = 100;  

     if (!m.empty())  

      cout << "Map is not empty." << endl;  

   return 0;  

}

Output:

Output

Map is empty

Map is not empty

Explanation:

In this example, we have taken a map m that has no elements. Therefore, the m.empty returns true, and it prints "Map is empty". After inserting a key-value pair 'n' = 100, the map is no longer empty, so m.empty returns false, and it prints "Map is not empty.".

Removing All Elements from a C++ Map Using empty and erase Function

Let us take an example to illustrate how to remove all elements from a map using the empty and erase functions in C++.

Example

Example

#include <iostream>  

#include <map>  

using namespace std;     //using standard namespace

int main ()    //main function

{  

  map<char,int> mymap;  

  mymap['x']=100;  

  mymap['y']=200;  

  mymap['z']=300;  

  while (!mymap.empty())  

  {  

    cout << mymap.begin()->first << " => " << mymap.begin()->second << '\n';  

    mymap.erase(mymap.begin());  

  }    

  return 0;  

}

Output:

Output

x => 100

y => 200

z => 300

Explanation:

In this example, we simply use the empty function in a 'while' loop and print the elements of the map until the map is not empty.

Inserting and Displaying Elements in a C++ Map After Checking for empty

Let us take an example to illustrate how to insert and display elements in a map using the empty function.

Example

Example

#include <iostream>  

#include <map>  

#include <string>  

  using namespace std;     //using standard namespace

  int main() {      //main function

  typedef map<string, int> phoneMap;  

   string name;  

   int number;  

   phoneMap phone;       

   if (phone.empty())  

      cout << "Map is empty. Please insert content! \n " << endl;  

   cout<<"Enter three sets of name and number: \n";  

   for(int i =0; i<3; i++)  

   {  

       cin>> name;      // Get key  

       cin>> number;    // Get value  

       phone[name] = number;   // Put them in map  

   }  

   if (!phone.empty())  

   {  

      cout<<"\nList of telephone numbers: \n";  

      phoneMap::iterator p;  

      for(p = phone.begin(); p!=phone.end(); p++)  

      {  

          cout<<(*p).first << " " <<(*p).second <<" \n ";  

      }  

   }   

   return 0;  

}

Output:

Output

Map is empty. Please insert content!

Enter three sets of name and number:

Jhony 555555

Peterson 111111

Michael 333333

List of telephone numbers:

Jhony 555555

Michael 333333

Peterson 111111

Explanation:

In this example, first, we create a phone map interactively with three names. After that, it checks whether the map is empty or not. Next, if the map is empty, it displays a message; otherwise, it displays all the names and their telephone numbers available in the map.

Conclusion

In conclusion, the C++ map::empty function provides a simple and efficient way to check whether a map contains any elements. It is simply a Boolean function that allows us to prevent errors based on operating on either the map or an empty map. The empty function is of constant time complexity and exception safe, as well as helping coders understand readability and map operations in STL maps. It is a constant-time, non-modifying function that is useful for controlling program flow, validating operations, and ensuring safe access to map elements.

C++ map empty function FAQs

1) What does the map::empty function do in C++?

In C++, the empty function determines whether a map contains any elements. It returns true when a map is empty (size = 0); otherwise, it returns false. It is also useful to prevent unsafe operations with maps that don't have any elements.

2) How does the map::empty function differ from the map::size function?

In C++, both terms can be used to determine whether a map has elements. However, the empty function is much more semantic and expresses intent directly. Using size == 0 does indeed work the same, but the empty function is preferred for ease and readability. The implementation of both functions internally executes in constant time complexity.

3) Can the empty function throw exceptions in C++?

No, the map::empty function is marked as noexcept in C++11 and later. It means that it guarantees not to throw exceptions under any circumstances. It ensures safe and predictable behavior during execution.

4) Does the empty function modify the map in any way?

No, the empty function will never change the map in any way. It is a const member function that will only check the state of the map, and it is safe to call as many times as we want without changing the content!

5) When should we be using empty in real applications?

We should use the empty function to predicate iterating over the map, accessing elements, or printing contents, avoiding a runtime error. It is common in applications, for example, to check if a cache, configuration, or session data is available. The empty function helps to increase safety and improve code clarity.

Input Required

This code uses input(). Please provide values below: