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
#include <bits/stdc++.h>
using namespace std;
string check_key(map< int , int > m, int key)
{
if (m.find(key) == m.end())
return "Not Present" ;
return "Present" ;
}
int main()
{
map< int , int > m;
m[1] = 4;
m[2] = 6;
m[4] = 6;
int check1 = 5, check2 = 4;
cout << check1 << ": " << check_key(m, check1) << '\n' ;
cout << check2 << ": " << check_key(m, check2);
}
|
unordered_map
#include <bits/stdc++.h>
using namespace std;
string check_key(unordered_map< int , int > m, int key)
{
if (m.find(key) == m.end())
return "Not Present" ;
return "Present" ;
}
int main()
{
unordered_map< int , int > m;
m[1] = 4;
m[2] = 6;
m[4] = 6;
int check1 = 5, check2 = 4;
cout << check1 << ": " << check_key(m, check1) << '\n' ;
cout << check2 << ": " << check_key(m, check2);
}
|
Output:
5: Not Present
4: Present
Approach 2nd:
we can also use the count function of the map in c++.
Implementation:
1. Map
C++
#include <bits/stdc++.h>
using namespace std;
string check_key(map< int , int > m, int key)
{
if (m.count(key) == 0)
return "Not Present" ;
return "Present" ;
}
int main()
{
map< int , int > m;
m[1] = 4;
m[2] = 6;
m[4] = 6;
int check1 = 5, check2 = 4;
cout << check1 << ": " << check_key(m, check1) << '\n' ;
cout << check2 << ": " << check_key(m, check2);
}
|
Output:
5: Not Present
4: Present
2. Unordered Map
C++
#include <bits/stdc++.h>
using namespace std;
string check_key(unordered_map< int , int > m, int key)
{
if (m.count(key) == 0)
return "Not Present" ;
return "Present" ;
}
int main()
{
unordered_map< int , int > m;
m[1] = 4;
m[2] = 6;
m[4] = 6;
int check1 = 5, check2 = 4;
cout << check1 << ": " << check_key(m, check1) << '\n' ;
cout << check2 << ": " << check_key(m, check2);
}
|
Output:
5: Not Present
4: Present
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@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.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!