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.
1 |
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,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
#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:
1 |
Element Found - First::1 |
Python Resources
- Best Python Tutorials on lists, dict, functions, iterators & many more.
- Data Analysis in Python using Pandas Dataframe - Top Tutorials
C++11 / C++14 Resources
- Best C++11 Tutorials on Topics like Smart Pointers, tuples, Unordered map / set, lambda function etc.
- C++11 Multi-threading Series
- C++ - Boost Library Tutorials
Leave a Reply