Home »
C++ STL
unordered_map find() Function in C++ with Examples
C++ unordered_map find() Function: Here, we will learn about the find() function, its usages, syntax and examples.
Submitted by Shivang Yadav, on July 20, 2022
unordered_map:
An unordered_map is a special type of container that stores data in the form of key-value pairs in an unordered manner. The key stored is used to identify the data value mapped to it uniquely.
std::unordered_map::find() Function
The find() function is used to check for the presence of the pair with the given key value in the unordered_map.
std::unordered_map::find() Function Syntax:
unordered_mapName.find(k);
// k is the key value to be found
Parameter(s): It accepts a single parameter which is the key to be searched for.
Return Value: It returns an iterator that points to the element's key value if it is found otherwise it returns the end of the map iterator.
Examples:
CASE 1:
Input: unordered_map = {{1, a}, {2, e}, {10, a}}
key = 2
Output: key-value present.
CASE 2:
Input: unordered_map ={{1, a}, {2, e}, {10, a}}
key = 5
Output: key-value not present.
C++ unordered_map find() Function Example
#include <iostream>
#include <unordered_map>
using namespace std;
int main()
{
unordered_map<int, char> myUnorderedMap = { { 1, 'a' }, { 5, 'x' }, { 9, 's' } };
cout << "The elements of unordered_map are ";
for (auto x : myUnorderedMap)
cout << x.first << " : " << x.second << "\t";
cout << endl;
int k = 9;
cout << "The element " << k << " is ";
(myUnorderedMap.find(k) == myUnorderedMap.end()) ? cout << "Not Present\n" : cout << "Present\n";
k = 67;
cout << "The element " << k << " is ";
(myUnorderedMap.find(k) == myUnorderedMap.end()) ? cout << "Not Present\n" : cout << "Present\n";
return 0;
}
Output:
The elements of unordered_map are 9 : s 5 : x 1 : a
The element 9 is Present
The element 67 is Not Present