What is the unordered_map::find() function in C++?

In this shot, we will learn how to use the unordered_map::find() function.

Introduction

The unordered_map::find() function is available in the <unordered_map> header file in C++.

The unordered_map::find() searches a specific key in the unordered map.

Syntax

The syntax of the unordered_map::find() function is given below:

Iterator find(K key);

Parameter

The unordered_map::find() method accepts the parameter mentioned below:

  • Key: The key to be searched for in the unordered map.

Return value

The unordered_map::find() returns one of the two values:

  • Iterator: An iterator to the element when the key exists in the unordered map.
  • Iterator: An iterator to the end of the map when the key does not exist in the unordered map.

Code

Let us have a look at the code now:

#include <iostream>
#include <unordered_map>
using namespace std;
int main()
{
unordered_map<int,int> umap ={
{12, 32},
{16, 899},
{89, 90},
{66, 46}
};
if(umap.find(51) == umap.end())
cout<<"The element with key = 51 is not present." << endl;
else
cout<<"The element with key = 51 is present."<<endl;
if(umap.find(89) == umap.end())
cout<<"The element with key = 89 is not present." << endl;
else
cout<<"The element with key = 89 is present." << endl;
return 0;
}

Explanation

  • In lines 1 and 2, we import the required header files.
  • In line 5, we make a main() function.
  • From lines 7 to 12, we initialize an unordered_map with integer type keys and string type values.
  • From lines 14 to 17, we used an if-else statement to check whether the element with the specified key is present or not using the unordered_map::find() function. Here, we observe that the key is not present, and the corresponding message is printed.
  • From lines 19 to 22, we use an if-else statement again to check whether the element with the specified key is present or not using the unordered_map::find() function. This time, the key is present in the unordered map, and the corresponding message is printed.

This is how we use the unordered_map::find() function in C++.

Free Resources