C++ Standard Library C++ STL Library

C++ unordered_map - find() Function



The C++ unordered_map::find function is used to search the container for a specified key and returns the iterator to it if found, else returns the iterator to unordered_map::end.

Syntax

iterator find (const key_type& k);
const_iterator find (const key_type& k) const;

Parameters

k Specify key to search for.

Return Value

An iterator to the key if k is found, or unordered_map::end if k is not found.

Time Complexity

Average case: Constant i.e, Θ(1).
Worst case: Linear i.e, Θ(n).

Example:

In the example below, the unordered_map::find function is used to find the specified key in uMap.

#include <iostream>
#include <unordered_map>
using namespace std;
 
int main (){
  unordered_map<int, string> uMap;
  unordered_map<int, string>::iterator it;
  
  uMap[101] = "John";
  uMap[102] = "Marry";
  uMap[103] = "Kim";
  uMap[104] = "Jo";
  uMap[105] = "Ramesh";

  it = uMap.find(101);
  uMap.erase(it);
  uMap.erase(uMap.find(104));

  cout<<"uMap contains: \n ";
  for(it = uMap.begin(); it != uMap.end(); ++it)
    cout<<it->first<<"  "<<it->second<<"\n ";

  return 0;
}

The output of the above code will be:

uMap contains: 
 105  Ramesh
 103  Kim
 102  Marry

❮ C++ <unordered_map> Library

5