Open In App

unordered_map find in C++ STL

Last Updated : 26 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, std::unordered_map::find function is used to search for a specific element using the key in an unordered map container. It is a member function of std::unordered_map container defined inside <unordered_map> header file.

Syntax

um.find(key);

Parameters

  • key: The key of the element to be searched.

Return Value

  • If the given key is found, it returns an iterator to that pair.
  • Otherwise, it returns the end iterator.

Example of unordered_map::find()

C++
// C++ program to demonstrate how to use 
// unordered_map::find() function
#include <bits/stdc++.h>
using namespace std;

void checkKey(unordered_map<int, string>& um, int key) {
  	 // Searching for element with key
    if (um.find(key) == um.end())
        cout << "Key " << key <<
          " Not Present\n";
    else
        cout << "Key " << key << 
          " Present\n";
}

int main() {
    unordered_map<int, string> um = {{12, "Geeks"},
                  {678, "Geeksfor"}, {88, "Gfg"}};

    // Key1 and key2 which have to search
    int key1 = 678;
    int key2 = 456;
	
  	checkKey(um, key1);
  	checkKey(um, key2);
	return 0;
}

Output
Key 678 Present
Key 456 Not Present

Time Complexity: O(1) on average. O(n) in worst case where n is the number of elements.
Space Complexity: O(1)


Next Article

Similar Reads