Check if a key is present in a C++ map
Hello guys, here in this article we will learn how to check if a key is present in a C++ map or not. So first of all, we need to learn what is a map. The map is a data structure that can store elements in a combination of a key-value and a mapped value.
Suppose we want to store the name and roll number of each student, then the map will look like below:
<4,Ram> <6,Shyam> <10,faiz> <16,Harpreet> <12,Shivam>
Creating map
map<data_type1,data_type2> map_name;
Inserting in map
We use built-in insert() function to insert an element in map.
map_name.insert({key,value});
Example
#include <iostream>
#include<map>
using namespace std;
int main() {
map<int,string> mp; //declaring map
mp.insert({1,"INDIA"}); //inserting in map
mp.insert({2,"CHINA"}); //inserting in map
mp.insert({3,"USA"}); //inserting in map
mp.insert({4,"RUSSIA"}); //inserting in map
for(auto i=mp.begin();i!=mp.end();i++)
{
cout << i->first <<" "<<i->second<<endl; //i->first will print key.
//i->second will print value.
}
return 0;
}1 INDIA 2 CHINA 3 USA 4 RUSSIA
In the above example, I have used an auto keyword you can read more about it by click here.
Now we want to check if a key is present in a C++ map.
for this, we will check if i->first is equal to a given (what we want to check) key.
#include <iostream>
#include<map>
using namespace std;
int main() {
map<int,string> mp;
mp.insert({1,"INDIA"}); //inserting in map.
mp.insert({2,"CHINA"}); //inserting in map.
mp.insert({3,"USA"}); //inserting in map.
mp.insert({4,"RUSSIA"}); //inserting in map.
mp.insert({5,"France"}); //inserting in map.
int key; // declaring key variable.
cout <<"enter key"<<endl;
cin>>key; // taking key as input.
bool ans=false; // declaring bool variable and assign it to false.
for(auto i=mp.begin();i!=mp.end();i++)
{
if(i->first==key)
ans=true; //if key is variable is present then assign ans to true.
}
if(ans) // if ans is true print key is present else not present
cout<<"Key :"<<key<<" is present"<<endl;
else
cout<<"Key :"<<key<<" is no present"<<endl;
return 0;
}Example 1
input 5 ouput Key :5 is present
Example 2
input 10 output Key :10 is no present
Thank you.
Also, read: C++ program to print only digits from a string
Leave a Reply