unordered_map empty() Function in C++ with Examples

C++ unordered_map empty() Function: Here, we will learn about the empty() function, its usages, syntax and examples.
Submitted by Shivang Yadav, on July 20, 2022

unordered_map:

An unordered_map is a special type of container that stores data in the form of key-value pairs in an unordered manner. The key stored is used to identify the data value mapped to it uniquely.

std::unordered_map::empty() Function

The empty() function is used to check whether the unordered_map is empty or not i.e., it checks if the size is zero or not. The method returns:

  • true: When the size is equal to 0.
  • false: When the size is not equal to 0.

std::unordered_map::empty() Function Syntax:

unordered_map.empty();

Parameter(s): It does not require any parameter to perform its task.

Return Value: It returns a Boolean value i.e., either true or false value.

Examples:

Case 1: 
Input: unordered_map = {{1. a}, {5, s}, {2, K}}
Output: false

Case 2:
Input: unordered_map = {}
Output: True

Now, let's see a working program to check if the unordered_map is empty or not using the empty a function.

C++ unordered_map empty() Function Example:

#include <iostream>
#include <unordered_map>
using namespace std;

int main()
{
    unordered_map<int, char> myUnorderedMap = { { 1, 'a' }, { 5, 'x' }, { 9, 's' } };

    cout << "Size of unordered_map " << myUnorderedMap.size() << endl;
    cout << "The elements of unordered_map are ";
    for (auto x : myUnorderedMap)
        cout << x.first << " : " << x.second << "\t";
    cout << endl;

    myUnorderedMap.clear();

    cout << "After using clear() method.\n";
    cout << "Size of unordered_map " << myUnorderedMap.size() << endl;
    cout << "The elements of unordered_map are ";
    for (auto x : myUnorderedMap)
        cout << x.first << " : " << x.second << "\t";
    cout << endl;

    return 0;
}

Output:

Size of unordered_map 3
The elements of unordered_map are 9 : s 5 : x   1 : a
After using clear() method.
Size of unordered_map 0
The elements of unordered_map are




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.