C++ Unordered_map Library - count() Function



Description

The C++ function std::unordered_map::count() returns the number of mapped values associated with key k.

As this container does not allow duplicates value is alway either 0 or 1.

Declaration

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

C++11

size_type count(const key_type& k) const;

Parameters

k − Key for search operation.

Return value

Returns 1 if container has value associated with key k otherwise 0.

Time complexity

Linear i.e. O(n)

Example

The following example shows the usage of std::unordered_map::count() 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}
            };

   if (um.count('a') == 1) {
     cout << "um['a'] = " << um.at('a') << endl;
   }

   if (um.count('z') == 0) {
     cout << "Value not present for key um['z']" << endl;
   }

   return 0;
}

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

um['a'] = 1
Value not present for key um['z']
unordered_map.htm
Advertisements