Check if a key is present in a C++ map or unordered_map

C++Server Side ProgrammingProgramming

In C++ the Maps and unordered maps are hash tables. They use some keys and their respective key values. Here we will see how to check whether a given key is present in the hash table or not. The code will be like below −

Example

 Live Demo

#include<iostream>
#include<map>
using namespace std;
string isPresent(map<string, int> m, string key) {
   if (m.find(key) == m.end())
   return "Not Present";
   return "Present";
}
int main() {
   map<string, int> my_map;
   my_map["first"] = 4;
   my_map["second"] = 6;
   my_map["third"] = 6;
   string check1 = "fifth", check2 = "third";
   cout << check1 << ": " << isPresent(my_map, check1) << endl;
   cout << check2 << ": " << isPresent(my_map, check2);
}

Output

fifth: Not Present
third: Present
raja
Published on 17-Dec-2019 12:45:01
Advertisements