C++ Unordered_map Library - clear() Function


Advertisements

Description

The C++ function std::unordered_map::clear() destroys the unordered_map by removing all elements and sets the size of unordered_map to zero.

Declaration

Following is the declaration for std::unordered_map::clear() function form std::unordered_map header.

C++11

void clear() noexcept;

Parameters

None

Return value

None

Exceptions

This member function never throws exception.

Time complexity

Linear i.e. O(n)

Example

The following example shows the usage of std::unordered_map::clear() function.

#include <iostream>
#include <unordered_map>

using namespace std;

int main(void) {
   unordered_map<char, int> um = {
            {'a', 1},
            {'b', 2},
            {'c', 3},
            {'d', 4},
            {'e', 5}
            };

   cout << "Initial size of unordered map = " << um.size() << endl;

   um.clear();

   cout << "Size of unordered map after clear operation = " << um.size() << endl;

   return 0;
}

Let us compile and run the above program, this will produce the following result −

Initial size of unordered map = 5
Size of unordered map after clear operation = 0
unordered_map.htm
Advertisements