Find Whether an Element Exists in std::map in C++
To check if a map contains a specific key, we can use the std::map::find() function along with the iterator that searches for the specific key in the map and prints the corresponding value if the key matches. If the key is not found, the find() function returns the iterator to the end.
C++ Program to Find Whether an Element Exists in std::map
The below example demonstrates how we can check if the map contains a specific key or not in C++.
// C++ Program to illustrate how to find whether an element
// exists in std::map
#include <iostream>
#include <map>
using namespace std;
int main()
{
// creating a map
map<int, string> mp = { { 1, "Apple" },
{ 2, "Banana" },
{ 3, "Orange" } };
// specific key to be searched
int key = 2;
// Checking if the map contains a specific key
auto it = mp.find(key);
if (it != mp.end()) {
// if key is found
cout << "Map contains key '" << key
<< "' with value: " << it->second << endl;
}
else {
// if key is not found
cout << "Map does not contain key '" << key << "'"
<< endl;
}
return 0;
}
Output
Map contains key '2' with value: Banana
Time Complexity: O(log(N))
Auxiliary Space: O(1)
Note: We can also use std::map::count() function to check if a map contains a specific key in C++.
How to Check if Map Contains a Specific Key in C++?
In C++, std::map is a container provided by the Standard Template Library (STL) that stores elements in key-value pairs, where the keys are sorted. In this article, we will learn how to find whether an element exists in std::map in C++.
Example:
Input: myMap = { {1,"Apple"}, {2,"Banana"},{3,"Orange"}}; Key = 2 Output: Key 2 is present in the map with a value banana.