C++ Standard Library C++ STL Library

C++ map - find() Function



The C++ 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 map::end.

Syntax

iterator find (const key_type& k);
const_iterator find (const key_type& k) const;
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 map::end if k is not found.

Time Complexity

Logarithmic i.e, Θ(log(n)).

Example:

In the example below, the map::find function is used to find the key in the map called MyMap.

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

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

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

  return 0;
}

The output of the above code will be:

MyMap contains: 
 102  Marry
 103  Kim
 105  Ramesh

❮ C++ <map> Library

5