How to find an element in unordered_map

In this article we will discuss how to find an element in an unordered_map.

An unordered_map store elements in key – value pair. Hence to search an element we need to search if the key exists in an unordered_map or not. For this unordered_map provides a member function find() i.e.

iterator find ( const key_type& k );

It accepts a key as an argument and returns an iterator i.e.

If the given key exists in map then, it will return an iterator pointing to the element. Otherwise, iterator pointing to the end of map.

Let’s see an example,

#include <iostream>
#include <unordered_map>
#include <string>

int main() {
	// Initialize an unordered_map through initializer_list
	std::unordered_map<std::string, int> wordMap( {
		{ "First", 1 }, { "Second",	2 }, { "Third", 3 }
												});

	// Declare an iterator to unordered_map
	std::unordered_map<std::string, int>::iterator it;

	// Find if an element with key "First" exists or not.
	// find() returns an iterator

	it = wordMap.find("First");

	// Check if iterator points to end of map
	if (it != wordMap.end())
	{
		std::cout << "Element Found - ";
		std::cout << it->first << "::" << it->second << std::endl;
	}
	else
	{
		std::cout << "Element Not Found" << std::endl;
	}

	return 0;
}

Ouput:
Element Found - First::1

 

 

Advertisements

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top