Check if a key is present in a C++ map or unordered_map
A C++ map and unordered_map are initialized to some keys and their respective mapped values.
Examples:
Input : Map : 1 -> 4, 2 -> 6, 4 -> 6 Check1 : 5, Check2 : 4 Output : 5 : Not present, 4 : Present
C++ implementation :
map
// CPP code to check if a // key is present in a map #include <bits/stdc++.h> using namespace std; // Function to check if the key is present or not string check_key(map<int, int> m, int key) { // Key is not present if (m.find(key) == m.end()) return "Not Present"; return "Present"; } // Driver int main() { map<int, int> m; // Initializing keys and mapped values m[1] = 4; m[2] = 6; m[4] = 6; // Keys to ce checked int check1 = 5, check2 = 4; // Function call cout << check1 << ": " << check_key(m, check1) << '\n'; cout << check2 << ": " << check_key(m, check2); } |
chevron_right
filter_none
unordered_map
// CPP code to check if a key is present // in an unordered_map #include <bits/stdc++.h> using namespace std; // Function to check if the key is present or not string check_key(unordered_map<int, int> m, int key) { // Key is not present if (m.find(key) == m.end()) return "Not Present"; return "Present"; } // Driver int main() { unordered_map<int, int> m; // Initialising keys and mapped values m[1] = 4; m[2] = 6; m[4] = 6; // Keys to ce checked int check1 = 5, check2 = 4; // Function call cout << check1 << ": " << check_key(m, check1) << '\n'; cout << check2 << ": " << check_key(m, check2); } |
chevron_right
filter_none
Output:
5: Not Present 4: Present
This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Recommended Posts:
- Check if the given string of words can be formed from words present in the dictionary
- Elements present in first array and not in second using STL in C++
- Count of words that are present in all the given sentences
- Count of elements of an array present in every row of NxM matrix
- Understanding ShellExecute function and it's application to open a list of URLs present in a file using C++ code
- Find the character in first string that is present at minimum index in second string
- Most frequent word in first String which is not present in second String
- NaN in C++ - What is it and how to check for it?
- Check if a given graph is Bipartite using DFS
- Check if two trees are Mirror
- Check mirror in n-ary tree
- Check whether two strings are anagrams of each other using unordered_map in C++
- Program to check if an Array is Palindrome or not using STL in C++
- Check for integer overflow on multiplication
- Check all the elements in an array are even using library in C++



