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

 

Do you want to Learn Modern C++ from best?

We have curated a list of Best C++ Courses, that will teach you the cutting edge Modern C++ from the absolute beginning to advanced level. It will also introduce to you the word of Smart Pointers, Move semantics, Rvalue, Lambda function, auto, Variadic template, range based for loops, Multi-threading and many other latest features of C++ i.e. from C++11 to C++20.

Check Detailed Reviews of Best Modern C++ Courses

Remember, C++ requires a lot of patience, persistence, and practice. So, start learning today.

Leave a Comment

Your email address will not be published.

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

Scroll to Top